home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib-tk / turtle.pyc (.txt) < prev   
Python Compiled Bytecode  |  2009-11-11  |  140KB  |  4,376 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. Turtle graphics is a popular way for introducing programming to
  6. kids. It was part of the original Logo programming language developed
  7. by Wally Feurzig and Seymour Papert in 1966.
  8.  
  9. Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
  10. the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
  11. the direction it is facing, drawing a line as it moves. Give it the
  12. command turtle.left(25), and it rotates in-place 25 degrees clockwise.
  13.  
  14. By combining together these and similar commands, intricate shapes and
  15. pictures can easily be drawn.
  16.  
  17. ----- turtle.py
  18.  
  19. This module is an extended reimplementation of turtle.py from the
  20. Python standard distribution up to Python 2.5. (See: http://www.python.org)
  21.  
  22. It tries to keep the merits of turtle.py and to be (nearly) 100%
  23. compatible with it. This means in the first place to enable the
  24. learning programmer to use all the commands, classes and methods
  25. interactively when using the module from within IDLE run with
  26. the -n switch.
  27.  
  28. Roughly it has the following features added:
  29.  
  30. - Better animation of the turtle movements, especially of turning the
  31.   turtle. So the turtles can more easily be used as a visual feedback
  32.   instrument by the (beginning) programmer.
  33.  
  34. - Different turtle shapes, gif-images as turtle shapes, user defined
  35.   and user controllable turtle shapes, among them compound
  36.   (multicolored) shapes. Turtle shapes can be stretched and tilted, which
  37.   makes turtles very versatile geometrical objects.
  38.  
  39. - Fine control over turtle movement and screen updates via delay(),
  40.   and enhanced tracer() and speed() methods.
  41.  
  42. - Aliases for the most commonly used commands, like fd for forward etc.,
  43.   following the early Logo traditions. This reduces the boring work of
  44.   typing long sequences of commands, which often occur in a natural way
  45.   when kids try to program fancy pictures on their first encounter with
  46.   turtle graphics.
  47.  
  48. - Turtles now have an undo()-method with configurable undo-buffer.
  49.  
  50. - Some simple commands/methods for creating event driven programs
  51.   (mouse-, key-, timer-events). Especially useful for programming games.
  52.  
  53. - A scrollable Canvas class. The default scrollable Canvas can be
  54.   extended interactively as needed while playing around with the turtle(s).
  55.  
  56. - A TurtleScreen class with methods controlling background color or
  57.   background image, window and canvas size and other properties of the
  58.   TurtleScreen.
  59.  
  60. - There is a method, setworldcoordinates(), to install a user defined
  61.   coordinate-system for the TurtleScreen.
  62.  
  63. - The implementation uses a 2-vector class named Vec2D, derived from tuple.
  64.   This class is public, so it can be imported by the application programmer,
  65.   which makes certain types of computations very natural and compact.
  66.  
  67. - Appearance of the TurtleScreen and the Turtles at startup/import can be
  68.   configured by means of a turtle.cfg configuration file.
  69.   The default configuration mimics the appearance of the old turtle module.
  70.  
  71. - If configured appropriately the module reads in docstrings from a docstring
  72.   dictionary in some different language, supplied separately  and replaces
  73.   the English ones by those read in. There is a utility function
  74.   write_docstringdict() to write a dictionary with the original (English)
  75.   docstrings to disc, so it can serve as a template for translations.
  76.  
  77. Behind the scenes there are some features included with possible
  78. extensions in in mind. These will be commented and documented elsewhere.
  79.  
  80. '''
  81. _ver = 'turtle 1.0b1 - for Python 2.6   -  30. 5. 2008, 18:08'
  82. import Tkinter as TK
  83. import types
  84. import math
  85. import time
  86. import os
  87. from os.path import isfile, split, join
  88. from copy import deepcopy
  89. from math import *
  90. _tg_classes = [
  91.     'ScrolledCanvas',
  92.     'TurtleScreen',
  93.     'Screen',
  94.     'RawTurtle',
  95.     'Turtle',
  96.     'RawPen',
  97.     'Pen',
  98.     'Shape',
  99.     'Vec2D']
  100. _tg_screen_functions = [
  101.     'addshape',
  102.     'bgcolor',
  103.     'bgpic',
  104.     'bye',
  105.     'clearscreen',
  106.     'colormode',
  107.     'delay',
  108.     'exitonclick',
  109.     'getcanvas',
  110.     'getshapes',
  111.     'listen',
  112.     'mode',
  113.     'onkey',
  114.     'onscreenclick',
  115.     'ontimer',
  116.     'register_shape',
  117.     'resetscreen',
  118.     'screensize',
  119.     'setup',
  120.     'setworldcoordinates',
  121.     'title',
  122.     'tracer',
  123.     'turtles',
  124.     'update',
  125.     'window_height',
  126.     'window_width']
  127. _tg_turtle_functions = [
  128.     'back',
  129.     'backward',
  130.     'begin_fill',
  131.     'begin_poly',
  132.     'bk',
  133.     'circle',
  134.     'clear',
  135.     'clearstamp',
  136.     'clearstamps',
  137.     'clone',
  138.     'color',
  139.     'degrees',
  140.     'distance',
  141.     'dot',
  142.     'down',
  143.     'end_fill',
  144.     'end_poly',
  145.     'fd',
  146.     'fill',
  147.     'fillcolor',
  148.     'forward',
  149.     'get_poly',
  150.     'getpen',
  151.     'getscreen',
  152.     'getturtle',
  153.     'goto',
  154.     'heading',
  155.     'hideturtle',
  156.     'home',
  157.     'ht',
  158.     'isdown',
  159.     'isvisible',
  160.     'left',
  161.     'lt',
  162.     'onclick',
  163.     'ondrag',
  164.     'onrelease',
  165.     'pd',
  166.     'pen',
  167.     'pencolor',
  168.     'pendown',
  169.     'pensize',
  170.     'penup',
  171.     'pos',
  172.     'position',
  173.     'pu',
  174.     'radians',
  175.     'right',
  176.     'reset',
  177.     'resizemode',
  178.     'rt',
  179.     'seth',
  180.     'setheading',
  181.     'setpos',
  182.     'setposition',
  183.     'settiltangle',
  184.     'setundobuffer',
  185.     'setx',
  186.     'sety',
  187.     'shape',
  188.     'shapesize',
  189.     'showturtle',
  190.     'speed',
  191.     'st',
  192.     'stamp',
  193.     'tilt',
  194.     'tiltangle',
  195.     'towards',
  196.     'tracer',
  197.     'turtlesize',
  198.     'undo',
  199.     'undobufferentries',
  200.     'up',
  201.     'width',
  202.     'window_height',
  203.     'window_width',
  204.     'write',
  205.     'xcor',
  206.     'ycor']
  207. _tg_utilities = [
  208.     'write_docstringdict',
  209.     'done',
  210.     'mainloop']
  211. _math_functions = [
  212.     'acos',
  213.     'asin',
  214.     'atan',
  215.     'atan2',
  216.     'ceil',
  217.     'cos',
  218.     'cosh',
  219.     'e',
  220.     'exp',
  221.     'fabs',
  222.     'floor',
  223.     'fmod',
  224.     'frexp',
  225.     'hypot',
  226.     'ldexp',
  227.     'log',
  228.     'log10',
  229.     'modf',
  230.     'pi',
  231.     'pow',
  232.     'sin',
  233.     'sinh',
  234.     'sqrt',
  235.     'tan',
  236.     'tanh']
  237. __all__ = _tg_classes + _tg_screen_functions + _tg_turtle_functions + _tg_utilities + _math_functions
  238. _alias_list = [
  239.     'addshape',
  240.     'backward',
  241.     'bk',
  242.     'fd',
  243.     'ht',
  244.     'lt',
  245.     'pd',
  246.     'pos',
  247.     'pu',
  248.     'rt',
  249.     'seth',
  250.     'setpos',
  251.     'setposition',
  252.     'st',
  253.     'turtlesize',
  254.     'up',
  255.     'width']
  256. _CFG = {
  257.     'width': 0.5,
  258.     'height': 0.75,
  259.     'canvwidth': 400,
  260.     'canvheight': 300,
  261.     'leftright': None,
  262.     'topbottom': None,
  263.     'mode': 'standard',
  264.     'colormode': 1,
  265.     'delay': 10,
  266.     'undobuffersize': 1000,
  267.     'shape': 'classic',
  268.     'pencolor': 'black',
  269.     'fillcolor': 'black',
  270.     'resizemode': 'noresize',
  271.     'visible': True,
  272.     'language': 'english',
  273.     'exampleturtle': 'turtle',
  274.     'examplescreen': 'screen',
  275.     'title': 'Python Turtle Graphics',
  276.     'using_IDLE': False }
  277.  
  278. def config_dict(filename):
  279.     '''Convert content of config-file into dictionary.'''
  280.     f = open(filename, 'r')
  281.     cfglines = f.readlines()
  282.     f.close()
  283.     cfgdict = { }
  284.     for line in cfglines:
  285.         line = line.strip()
  286.         if not line or line.startswith('#'):
  287.             continue
  288.         
  289.         
  290.         try:
  291.             (key, value) = line.split('=')
  292.         except:
  293.             print 'Bad line in config-file %s:\n%s' % (filename, line)
  294.             continue
  295.  
  296.         key = key.strip()
  297.         value = value.strip()
  298.         if value in ('True', 'False', 'None', "''", '""'):
  299.             value = eval(value)
  300.         else:
  301.             
  302.             try:
  303.                 if '.' in value:
  304.                     value = float(value)
  305.                 else:
  306.                     value = int(value)
  307.             except:
  308.                 pass
  309.  
  310.         cfgdict[key] = value
  311.     
  312.     return cfgdict
  313.  
  314.  
  315. def readconfig(cfgdict):
  316.     """Read config-files, change configuration-dict accordingly.
  317.  
  318.     If there is a turtle.cfg file in the current working directory,
  319.     read it from there. If this contains an importconfig-value,
  320.     say 'myway', construct filename turtle_mayway.cfg else use
  321.     turtle.cfg and read it from the import-directory, where
  322.     turtle.py is located.
  323.     Update configuration dictionary first according to config-file,
  324.     in the import directory, then according to config-file in the
  325.     current working directory.
  326.     If no config-file is found, the default configuration is used.
  327.     """
  328.     default_cfg = 'turtle.cfg'
  329.     cfgdict1 = { }
  330.     cfgdict2 = { }
  331.     if isfile(default_cfg):
  332.         cfgdict1 = config_dict(default_cfg)
  333.     
  334.     if 'importconfig' in cfgdict1:
  335.         default_cfg = 'turtle_%s.cfg' % cfgdict1['importconfig']
  336.     
  337.     
  338.     try:
  339.         (head, tail) = split(__file__)
  340.         cfg_file2 = join(head, default_cfg)
  341.     except:
  342.         cfg_file2 = ''
  343.  
  344.     if isfile(cfg_file2):
  345.         cfgdict2 = config_dict(cfg_file2)
  346.     
  347.     _CFG.update(cfgdict2)
  348.     _CFG.update(cfgdict1)
  349.  
  350.  
  351. try:
  352.     readconfig(_CFG)
  353. except:
  354.     print 'No configfile read, reason unknown'
  355.  
  356.  
  357. class Vec2D(tuple):
  358.     '''A 2 dimensional vector class, used as a helper class
  359.     for implementing turtle graphics.
  360.     May be useful for turtle graphics programs also.
  361.     Derived from tuple, so a vector is a tuple!
  362.  
  363.     Provides (for a, b vectors, k number):
  364.        a+b vector addition
  365.        a-b vector subtraction
  366.        a*b inner product
  367.        k*a and a*k multiplication with scalar
  368.        |a| absolute value of a
  369.        a.rotate(angle) rotation
  370.     '''
  371.     
  372.     def __new__(cls, x, y):
  373.         return tuple.__new__(cls, (x, y))
  374.  
  375.     
  376.     def __add__(self, other):
  377.         return Vec2D(self[0] + other[0], self[1] + other[1])
  378.  
  379.     
  380.     def __mul__(self, other):
  381.         if isinstance(other, Vec2D):
  382.             return self[0] * other[0] + self[1] * other[1]
  383.         return Vec2D(self[0] * other, self[1] * other)
  384.  
  385.     
  386.     def __rmul__(self, other):
  387.         if isinstance(other, int) or isinstance(other, float):
  388.             return Vec2D(self[0] * other, self[1] * other)
  389.  
  390.     
  391.     def __sub__(self, other):
  392.         return Vec2D(self[0] - other[0], self[1] - other[1])
  393.  
  394.     
  395.     def __neg__(self):
  396.         return Vec2D(-self[0], -self[1])
  397.  
  398.     
  399.     def __abs__(self):
  400.         return (self[0] ** 2 + self[1] ** 2) ** 0.5
  401.  
  402.     
  403.     def rotate(self, angle):
  404.         '''rotate self counterclockwise by angle
  405.         '''
  406.         perp = Vec2D(-self[1], self[0])
  407.         angle = angle * math.pi / 180
  408.         c = math.cos(angle)
  409.         s = math.sin(angle)
  410.         return Vec2D(self[0] * c + perp[0] * s, self[1] * c + perp[1] * s)
  411.  
  412.     
  413.     def __getnewargs__(self):
  414.         return (self[0], self[1])
  415.  
  416.     
  417.     def __repr__(self):
  418.         return '(%.2f,%.2f)' % self
  419.  
  420.  
  421.  
  422. def __methodDict(cls, _dict):
  423.     '''helper function for Scrolled Canvas'''
  424.     baseList = list(cls.__bases__)
  425.     baseList.reverse()
  426.     for _super in baseList:
  427.         __methodDict(_super, _dict)
  428.     
  429.     for key, value in cls.__dict__.items():
  430.         if type(value) == types.FunctionType:
  431.             _dict[key] = value
  432.             continue
  433.     
  434.  
  435.  
  436. def __methods(cls):
  437.     '''helper function for Scrolled Canvas'''
  438.     _dict = { }
  439.     __methodDict(cls, _dict)
  440.     return _dict.keys()
  441.  
  442. __stringBody = 'def %(method)s(self, *args, **kw): return ' + 'self.%(attribute)s.%(method)s(*args, **kw)'
  443.  
  444. def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
  445.     '''Helper functions for Scrolled Canvas, used to forward
  446.     ScrolledCanvas-methods to Tkinter.Canvas class.
  447.     '''
  448.     _dict = { }
  449.     __methodDict(toClass, _dict)
  450.     for ex in _dict.keys():
  451.         if ex[:1] == '_' or ex[-1:] == '_':
  452.             del _dict[ex]
  453.             continue
  454.     
  455.     for ex in exclude:
  456.         if _dict.has_key(ex):
  457.             del _dict[ex]
  458.             continue
  459.     
  460.     for ex in __methods(fromClass):
  461.         if _dict.has_key(ex):
  462.             del _dict[ex]
  463.             continue
  464.     
  465.     for method, func in _dict.items():
  466.         d = {
  467.             'method': method,
  468.             'func': func }
  469.         if type(toPart) == types.StringType:
  470.             execString = __stringBody % {
  471.                 'method': method,
  472.                 'attribute': toPart }
  473.         
  474.         exec execString in d
  475.         fromClass.__dict__[method] = d[method]
  476.     
  477.  
  478.  
  479. class ScrolledCanvas(TK.Frame):
  480.     """Modeled after the scrolled canvas class from Grayons's Tkinter book.
  481.  
  482.     Used as the default canvas, which pops up automatically when
  483.     using turtle graphics functions or the Turtle class.
  484.     """
  485.     
  486.     def __init__(self, master, width = 500, height = 350, canvwidth = 600, canvheight = 500):
  487.         TK.Frame.__init__(self, master, width = width, height = height)
  488.         self._rootwindow = self.winfo_toplevel()
  489.         self.width = width
  490.         self.height = height
  491.         self.canvwidth = canvwidth
  492.         self.canvheight = canvheight
  493.         self.bg = 'white'
  494.         self._canvas = TK.Canvas(master, width = width, height = height, bg = self.bg, relief = TK.SUNKEN, borderwidth = 2)
  495.         self.hscroll = TK.Scrollbar(master, command = self._canvas.xview, orient = TK.HORIZONTAL)
  496.         self.vscroll = TK.Scrollbar(master, command = self._canvas.yview)
  497.         self._canvas.configure(xscrollcommand = self.hscroll.set, yscrollcommand = self.vscroll.set)
  498.         self.rowconfigure(0, weight = 1, minsize = 0)
  499.         self.columnconfigure(0, weight = 1, minsize = 0)
  500.         self._canvas.grid(padx = 1, in_ = self, pady = 1, row = 0, column = 0, rowspan = 1, columnspan = 1, sticky = 'news')
  501.         self.vscroll.grid(padx = 1, in_ = self, pady = 1, row = 0, column = 1, rowspan = 1, columnspan = 1, sticky = 'news')
  502.         self.hscroll.grid(padx = 1, in_ = self, pady = 1, row = 1, column = 0, rowspan = 1, columnspan = 1, sticky = 'news')
  503.         self.reset()
  504.         self._rootwindow.bind('<Configure>', self.onResize)
  505.  
  506.     
  507.     def reset(self, canvwidth = None, canvheight = None, bg = None):
  508.         '''Adjust canvas and scrollbars according to given canvas size.'''
  509.         if canvwidth:
  510.             self.canvwidth = canvwidth
  511.         
  512.         if canvheight:
  513.             self.canvheight = canvheight
  514.         
  515.         if bg:
  516.             self.bg = bg
  517.         
  518.         self._canvas.config(bg = bg, scrollregion = (-(self.canvwidth) // 2, -(self.canvheight) // 2, self.canvwidth // 2, self.canvheight // 2))
  519.         self._canvas.xview_moveto(0.5 * ((self.canvwidth - self.width) + 30) / self.canvwidth)
  520.         self._canvas.yview_moveto(0.5 * ((self.canvheight - self.height) + 30) / self.canvheight)
  521.         self.adjustScrolls()
  522.  
  523.     
  524.     def adjustScrolls(self):
  525.         ''' Adjust scrollbars according to window- and canvas-size.
  526.         '''
  527.         cwidth = self._canvas.winfo_width()
  528.         cheight = self._canvas.winfo_height()
  529.         self._canvas.xview_moveto(0.5 * (self.canvwidth - cwidth) / self.canvwidth)
  530.         self._canvas.yview_moveto(0.5 * (self.canvheight - cheight) / self.canvheight)
  531.         if cwidth < self.canvwidth or cheight < self.canvheight:
  532.             self.hscroll.grid(padx = 1, in_ = self, pady = 1, row = 1, column = 0, rowspan = 1, columnspan = 1, sticky = 'news')
  533.             self.vscroll.grid(padx = 1, in_ = self, pady = 1, row = 0, column = 1, rowspan = 1, columnspan = 1, sticky = 'news')
  534.         else:
  535.             self.hscroll.grid_forget()
  536.             self.vscroll.grid_forget()
  537.  
  538.     
  539.     def onResize(self, event):
  540.         '''self-explanatory'''
  541.         self.adjustScrolls()
  542.  
  543.     
  544.     def bbox(self, *args):
  545.         """ 'forward' method, which canvas itself has inherited...
  546.         """
  547.         return self._canvas.bbox(*args)
  548.  
  549.     
  550.     def cget(self, *args, **kwargs):
  551.         """ 'forward' method, which canvas itself has inherited...
  552.         """
  553.         return self._canvas.cget(*args, **kwargs)
  554.  
  555.     
  556.     def config(self, *args, **kwargs):
  557.         """ 'forward' method, which canvas itself has inherited...
  558.         """
  559.         self._canvas.config(*args, **kwargs)
  560.  
  561.     
  562.     def bind(self, *args, **kwargs):
  563.         """ 'forward' method, which canvas itself has inherited...
  564.         """
  565.         self._canvas.bind(*args, **kwargs)
  566.  
  567.     
  568.     def unbind(self, *args, **kwargs):
  569.         """ 'forward' method, which canvas itself has inherited...
  570.         """
  571.         self._canvas.unbind(*args, **kwargs)
  572.  
  573.     
  574.     def focus_force(self):
  575.         """ 'forward' method, which canvas itself has inherited...
  576.         """
  577.         self._canvas.focus_force()
  578.  
  579.  
  580. __forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')
  581.  
  582. class _Root(TK.Tk):
  583.     '''Root class for Screen based on Tkinter.'''
  584.     
  585.     def __init__(self):
  586.         TK.Tk.__init__(self)
  587.  
  588.     
  589.     def setupcanvas(self, width, height, cwidth, cheight):
  590.         self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight)
  591.         self._canvas.pack(expand = 1, fill = 'both')
  592.  
  593.     
  594.     def _getcanvas(self):
  595.         return self._canvas
  596.  
  597.     
  598.     def set_geometry(self, width, height, startx, starty):
  599.         self.geometry('%dx%d%+d%+d' % (width, height, startx, starty))
  600.  
  601.     
  602.     def ondestroy(self, destroy):
  603.         self.wm_protocol('WM_DELETE_WINDOW', destroy)
  604.  
  605.     
  606.     def win_width(self):
  607.         return self.winfo_screenwidth()
  608.  
  609.     
  610.     def win_height(self):
  611.         return self.winfo_screenheight()
  612.  
  613.  
  614. Canvas = TK.Canvas
  615.  
  616. class TurtleScreenBase(object):
  617.     '''Provide the basic graphics functionality.
  618.        Interface between Tkinter and turtle.py.
  619.  
  620.        To port turtle.py to some different graphics toolkit
  621.        a corresponding TurtleScreenBase class has to be implemented.
  622.     '''
  623.     
  624.     def _blankimage():
  625.         '''return a blank image object
  626.         '''
  627.         img = TK.PhotoImage(width = 1, height = 1)
  628.         img.blank()
  629.         return img
  630.  
  631.     _blankimage = staticmethod(_blankimage)
  632.     
  633.     def _image(filename):
  634.         '''return an image object containing the
  635.         imagedata from a gif-file named filename.
  636.         '''
  637.         return TK.PhotoImage(file = filename)
  638.  
  639.     _image = staticmethod(_image)
  640.     
  641.     def __init__(self, cv):
  642.         self.cv = cv
  643.         if isinstance(cv, ScrolledCanvas):
  644.             w = self.cv.canvwidth
  645.             h = self.cv.canvheight
  646.         else:
  647.             w = int(self.cv.cget('width'))
  648.             h = int(self.cv.cget('height'))
  649.             self.cv.config(scrollregion = (-w // 2, -h // 2, w // 2, h // 2))
  650.         self.canvwidth = w
  651.         self.canvheight = h
  652.         self.xscale = self.yscale = 1
  653.  
  654.     
  655.     def _createpoly(self):
  656.         '''Create an invisible polygon item on canvas self.cv)
  657.         '''
  658.         return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill = '', outline = '')
  659.  
  660.     
  661.     def _drawpoly(self, polyitem, coordlist, fill = None, outline = None, width = None, top = False):
  662.         """Configure polygonitem polyitem according to provided
  663.         arguments:
  664.         coordlist is sequence of coordinates
  665.         fill is filling color
  666.         outline is outline color
  667.         top is a boolean value, which specifies if polyitem
  668.         will be put on top of the canvas' displaylist so it
  669.         will not be covered by other items.
  670.         """
  671.         cl = []
  672.         for x, y in coordlist:
  673.             cl.append(x * self.xscale)
  674.             cl.append(-y * self.yscale)
  675.         
  676.         self.cv.coords(polyitem, *cl)
  677.         if fill is not None:
  678.             self.cv.itemconfigure(polyitem, fill = fill)
  679.         
  680.         if outline is not None:
  681.             self.cv.itemconfigure(polyitem, outline = outline)
  682.         
  683.         if width is not None:
  684.             self.cv.itemconfigure(polyitem, width = width)
  685.         
  686.         if top:
  687.             self.cv.tag_raise(polyitem)
  688.         
  689.  
  690.     
  691.     def _createline(self):
  692.         '''Create an invisible line item on canvas self.cv)
  693.         '''
  694.         return self.cv.create_line(0, 0, 0, 0, fill = '', width = 2, capstyle = TK.ROUND)
  695.  
  696.     
  697.     def _drawline(self, lineitem, coordlist = None, fill = None, width = None, top = False):
  698.         """Configure lineitem according to provided arguments:
  699.         coordlist is sequence of coordinates
  700.         fill is drawing color
  701.         width is width of drawn line.
  702.         top is a boolean value, which specifies if polyitem
  703.         will be put on top of the canvas' displaylist so it
  704.         will not be covered by other items.
  705.         """
  706.         if coordlist is not None:
  707.             cl = []
  708.             for x, y in coordlist:
  709.                 cl.append(x * self.xscale)
  710.                 cl.append(-y * self.yscale)
  711.             
  712.             self.cv.coords(lineitem, *cl)
  713.         
  714.         if fill is not None:
  715.             self.cv.itemconfigure(lineitem, fill = fill)
  716.         
  717.         if width is not None:
  718.             self.cv.itemconfigure(lineitem, width = width)
  719.         
  720.         if top:
  721.             self.cv.tag_raise(lineitem)
  722.         
  723.  
  724.     
  725.     def _delete(self, item):
  726.         '''Delete graphics item from canvas.
  727.         If item is"all" delete all graphics items.
  728.         '''
  729.         self.cv.delete(item)
  730.  
  731.     
  732.     def _update(self):
  733.         '''Redraw graphics items on canvas
  734.         '''
  735.         self.cv.update()
  736.  
  737.     
  738.     def _delay(self, delay):
  739.         '''Delay subsequent canvas actions for delay ms.'''
  740.         self.cv.after(delay)
  741.  
  742.     
  743.     def _iscolorstring(self, color):
  744.         '''Check if the string color is a legal Tkinter color string.
  745.         '''
  746.         
  747.         try:
  748.             rgb = self.cv.winfo_rgb(color)
  749.             ok = True
  750.         except TK.TclError:
  751.             ok = False
  752.  
  753.         return ok
  754.  
  755.     
  756.     def _bgcolor(self, color = None):
  757.         """Set canvas' backgroundcolor if color is not None,
  758.         else return backgroundcolor."""
  759.         if color is not None:
  760.             self.cv.config(bg = color)
  761.             self._update()
  762.         else:
  763.             return self.cv.cget('bg')
  764.         return color is not None
  765.  
  766.     
  767.     def _write(self, pos, txt, align, font, pencolor):
  768.         """Write txt at pos in canvas with specified font
  769.         and color.
  770.         Return text item and x-coord of right bottom corner
  771.         of text's bounding box."""
  772.         (x, y) = pos
  773.         x = x * self.xscale
  774.         y = y * self.yscale
  775.         anchor = {
  776.             'left': 'sw',
  777.             'center': 's',
  778.             'right': 'se' }
  779.         item = self.cv.create_text(x - 1, -y, text = txt, anchor = anchor[align], fill = pencolor, font = font)
  780.         (x0, y0, x1, y1) = self.cv.bbox(item)
  781.         self.cv.update()
  782.         return (item, x1 - 1)
  783.  
  784.     
  785.     def _onclick(self, item, fun, num = 1, add = None):
  786.         '''Bind fun to mouse-click event on turtle.
  787.         fun must be a function with two arguments, the coordinates
  788.         of the clicked point on the canvas.
  789.         num, the number of the mouse-button defaults to 1
  790.         '''
  791.         pass
  792.  
  793.     
  794.     def _onrelease(self, item, fun, num = 1, add = None):
  795.         '''Bind fun to mouse-button-release event on turtle.
  796.         fun must be a function with two arguments, the coordinates
  797.         of the point on the canvas where mouse button is released.
  798.         num, the number of the mouse-button defaults to 1
  799.  
  800.         If a turtle is clicked, first _onclick-event will be performed,
  801.         then _onscreensclick-event.
  802.         '''
  803.         pass
  804.  
  805.     
  806.     def _ondrag(self, item, fun, num = 1, add = None):
  807.         '''Bind fun to mouse-move-event (with pressed mouse button) on turtle.
  808.         fun must be a function with two arguments, the coordinates of the
  809.         actual mouse position on the canvas.
  810.         num, the number of the mouse-button defaults to 1
  811.  
  812.         Every sequence of mouse-move-events on a turtle is preceded by a
  813.         mouse-click event on that turtle.
  814.         '''
  815.         pass
  816.  
  817.     
  818.     def _onscreenclick(self, fun, num = 1, add = None):
  819.         '''Bind fun to mouse-click event on canvas.
  820.         fun must be a function with two arguments, the coordinates
  821.         of the clicked point on the canvas.
  822.         num, the number of the mouse-button defaults to 1
  823.  
  824.         If a turtle is clicked, first _onclick-event will be performed,
  825.         then _onscreensclick-event.
  826.         '''
  827.         pass
  828.  
  829.     
  830.     def _onkey(self, fun, key):
  831.         '''Bind fun to key-release event of key.
  832.         Canvas must have focus. See method listen
  833.         '''
  834.         pass
  835.  
  836.     
  837.     def _listen(self):
  838.         '''Set focus on canvas (in order to collect key-events)
  839.         '''
  840.         self.cv.focus_force()
  841.  
  842.     
  843.     def _ontimer(self, fun, t):
  844.         '''Install a timer, which calls fun after t milliseconds.
  845.         '''
  846.         if t == 0:
  847.             self.cv.after_idle(fun)
  848.         else:
  849.             self.cv.after(t, fun)
  850.  
  851.     
  852.     def _createimage(self, image):
  853.         '''Create and return image item on canvas.
  854.         '''
  855.         return self.cv.create_image(0, 0, image = image)
  856.  
  857.     
  858.     def _drawimage(self, item, .2, image):
  859.         '''Configure image item as to draw image object
  860.         at position (x,y) on canvas)
  861.         '''
  862.         (x, y) = .2
  863.         self.cv.coords(item, (x * self.xscale, -y * self.yscale))
  864.         self.cv.itemconfig(item, image = image)
  865.  
  866.     
  867.     def _setbgpic(self, item, image):
  868.         '''Configure image item as to draw image object
  869.         at center of canvas. Set item to the first item
  870.         in the displaylist, so it will be drawn below
  871.         any other item .'''
  872.         self.cv.itemconfig(item, image = image)
  873.         self.cv.tag_lower(item)
  874.  
  875.     
  876.     def _type(self, item):
  877.         """Return 'line' or 'polygon' or 'image' depending on
  878.         type of item.
  879.         """
  880.         return self.cv.type(item)
  881.  
  882.     
  883.     def _pointlist(self, item):
  884.         '''returns list of coordinate-pairs of points of item
  885.         Example (for insiders):
  886.         >>> from turtle import *
  887.         >>> getscreen()._pointlist(getturtle().turtle._item)
  888.         [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
  889.         (9.9999999999999982, 0.0)]
  890.         >>> '''
  891.         cl = self.cv.coords(item)
  892.         pl = [ (cl[i], -cl[i + 1]) for i in range(0, len(cl), 2) ]
  893.         return pl
  894.  
  895.     
  896.     def _setscrollregion(self, srx1, sry1, srx2, sry2):
  897.         self.cv.config(scrollregion = (srx1, sry1, srx2, sry2))
  898.  
  899.     
  900.     def _rescale(self, xscalefactor, yscalefactor):
  901.         items = self.cv.find_all()
  902.         for item in items:
  903.             coordinates = self.cv.coords(item)
  904.             newcoordlist = []
  905.             while coordinates:
  906.                 (x, y) = coordinates[:2]
  907.                 newcoordlist.append(x * xscalefactor)
  908.                 newcoordlist.append(y * yscalefactor)
  909.                 coordinates = coordinates[2:]
  910.             self.cv.coords(item, *newcoordlist)
  911.         
  912.  
  913.     
  914.     def _resize(self, canvwidth = None, canvheight = None, bg = None):
  915.         '''Resize the canvas the turtles are drawing on. Does
  916.         not alter the drawing window.
  917.         '''
  918.         if not isinstance(self.cv, ScrolledCanvas):
  919.             return (self.canvwidth, self.canvheight)
  920.         if canvwidth is None and canvheight is None and bg is None:
  921.             return (self.cv.canvwidth, self.cv.canvheight)
  922.         if canvheight is not None:
  923.             self.canvheight = canvheight
  924.         
  925.         self.cv.reset(canvwidth, canvheight, bg)
  926.  
  927.     
  928.     def _window_size(self):
  929.         ''' Return the width and height of the turtle window.
  930.         '''
  931.         width = self.cv.winfo_width()
  932.         if width <= 1:
  933.             width = self.cv['width']
  934.         
  935.         height = self.cv.winfo_height()
  936.         if height <= 1:
  937.             height = self.cv['height']
  938.         
  939.         return (width, height)
  940.  
  941.  
  942.  
  943. class Terminator(Exception):
  944.     '''Will be raised in TurtleScreen.update, if _RUNNING becomes False.
  945.  
  946.     Thus stops execution of turtle graphics script. Main purpose: use in
  947.     in the Demo-Viewer turtle.Demo.py.
  948.     '''
  949.     pass
  950.  
  951.  
  952. class TurtleGraphicsError(Exception):
  953.     '''Some TurtleGraphics Error
  954.     '''
  955.     pass
  956.  
  957.  
  958. class Shape(object):
  959.     '''Data structure modeling shapes.
  960.  
  961.     attribute _type is one of "polygon", "image", "compound"
  962.     attribute _data is - depending on _type a poygon-tuple,
  963.     an image or a list constructed using the addcomponent method.
  964.     '''
  965.     
  966.     def __init__(self, type_, data = None):
  967.         self._type = type_
  968.         if type_ == 'polygon':
  969.             if isinstance(data, list):
  970.                 data = tuple(data)
  971.             
  972.         elif type_ == 'image':
  973.             if isinstance(data, str):
  974.                 if data.lower().endswith('.gif') and isfile(data):
  975.                     data = TurtleScreen._image(data)
  976.                 
  977.             
  978.         elif type_ == 'compound':
  979.             data = []
  980.         else:
  981.             raise TurtleGraphicsError('There is no shape type %s' % type_)
  982.         self._data = type_ == 'polygon'
  983.  
  984.     
  985.     def addcomponent(self, poly, fill, outline = None):
  986.         '''Add component to a shape of type compound.
  987.  
  988.         Arguments: poly is a polygon, i. e. a tuple of number pairs.
  989.         fill is the fillcolor of the component,
  990.         outline is the outline color of the component.
  991.  
  992.         call (for a Shapeobject namend s):
  993.         --   s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
  994.  
  995.         Example:
  996.         >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
  997.         >>> s = Shape("compound")
  998.         >>> s.addcomponent(poly, "red", "blue")
  999.         ### .. add more components and then use register_shape()
  1000.         '''
  1001.         if self._type != 'compound':
  1002.             raise TurtleGraphicsError('Cannot add component to %s Shape' % self._type)
  1003.         self._type != 'compound'
  1004.         if outline is None:
  1005.             outline = fill
  1006.         
  1007.         self._data.append([
  1008.             poly,
  1009.             fill,
  1010.             outline])
  1011.  
  1012.  
  1013.  
  1014. class Tbuffer(object):
  1015.     '''Ring buffer used as undobuffer for RawTurtle objects.'''
  1016.     
  1017.     def __init__(self, bufsize = 10):
  1018.         self.bufsize = bufsize
  1019.         self.buffer = [
  1020.             [
  1021.                 None]] * bufsize
  1022.         self.ptr = -1
  1023.         self.cumulate = False
  1024.  
  1025.     
  1026.     def reset(self, bufsize = None):
  1027.         if bufsize is None:
  1028.             for i in range(self.bufsize):
  1029.                 self.buffer[i] = [
  1030.                     None]
  1031.             
  1032.         else:
  1033.             self.bufsize = bufsize
  1034.             self.buffer = [
  1035.                 [
  1036.                     None]] * bufsize
  1037.         self.ptr = -1
  1038.  
  1039.     
  1040.     def push(self, item):
  1041.         if self.bufsize > 0:
  1042.             if not self.cumulate:
  1043.                 self.ptr = (self.ptr + 1) % self.bufsize
  1044.                 self.buffer[self.ptr] = item
  1045.             else:
  1046.                 self.buffer[self.ptr].append(item)
  1047.         
  1048.  
  1049.     
  1050.     def pop(self):
  1051.         if self.bufsize > 0:
  1052.             item = self.buffer[self.ptr]
  1053.             if item is None:
  1054.                 return None
  1055.             self.buffer[self.ptr] = [
  1056.                 None]
  1057.             self.ptr = (self.ptr - 1) % self.bufsize
  1058.             return item
  1059.         self.bufsize > 0
  1060.  
  1061.     
  1062.     def nr_of_items(self):
  1063.         return self.bufsize - self.buffer.count([
  1064.             None])
  1065.  
  1066.     
  1067.     def __repr__(self):
  1068.         return str(self.buffer) + ' ' + str(self.ptr)
  1069.  
  1070.  
  1071.  
  1072. class TurtleScreen(TurtleScreenBase):
  1073.     '''Provides screen oriented methods like setbg etc.
  1074.  
  1075.     Only relies upon the methods of TurtleScreenBase and NOT
  1076.     upon components of the underlying graphics toolkit -
  1077.     which is Tkinter in this case.
  1078.     '''
  1079.     _RUNNING = True
  1080.     
  1081.     def __init__(self, cv, mode = _CFG['mode'], colormode = _CFG['colormode'], delay = _CFG['delay']):
  1082.         self._shapes = {
  1083.             'arrow': Shape('polygon', ((-10, 0), (10, 0), (0, 10))),
  1084.             'turtle': Shape('polygon', ((0, 16), (-2, 14), (-1, 10), (-4, 7), (-7, 9), (-9, 8), (-6, 5), (-7, 1), (-5, -3), (-8, -6), (-6, -8), (-4, -5), (0, -7), (4, -5), (6, -8), (8, -6), (5, -3), (7, 1), (6, 5), (9, 8), (7, 9), (4, 7), (1, 10), (2, 14))),
  1085.             'circle': Shape('polygon', ((10, 0), (9.51, 3.09), (8.09, 5.88), (5.88, 8.09), (3.09, 9.51), (0, 10), (-3.09, 9.51), (-5.88, 8.09), (-8.09, 5.88), (-9.51, 3.09), (-10, 0), (-9.51, -3.09), (-8.09, -5.88), (-5.88, -8.09), (-3.09, -9.51), (-0, -10), (3.09, -9.51), (5.88, -8.09), (8.09, -5.88), (9.51, -3.09))),
  1086.             'square': Shape('polygon', ((10, -10), (10, 10), (-10, 10), (-10, -10))),
  1087.             'triangle': Shape('polygon', ((10, -5.77), (0, 11.55), (-10, -5.77))),
  1088.             'classic': Shape('polygon', ((0, 0), (-5, -9), (0, -7), (5, -9))),
  1089.             'blank': Shape('image', self._blankimage()) }
  1090.         self._bgpics = {
  1091.             'nopic': '' }
  1092.         TurtleScreenBase.__init__(self, cv)
  1093.         self._mode = mode
  1094.         self._delayvalue = delay
  1095.         self._colormode = _CFG['colormode']
  1096.         self._keys = []
  1097.         self.clear()
  1098.  
  1099.     
  1100.     def clear(self):
  1101.         '''Delete all drawings and all turtles from the TurtleScreen.
  1102.  
  1103.         Reset empty TurtleScreen to its initial state: white background,
  1104.         no backgroundimage, no eventbindings and tracing on.
  1105.  
  1106.         No argument.
  1107.  
  1108.         Example (for a TurtleScreen instance named screen):
  1109.         screen.clear()
  1110.  
  1111.         Note: this method is not available as function.
  1112.         '''
  1113.         self._delayvalue = _CFG['delay']
  1114.         self._colormode = _CFG['colormode']
  1115.         self._delete('all')
  1116.         self._bgpic = self._createimage('')
  1117.         self._bgpicname = 'nopic'
  1118.         self._tracing = 1
  1119.         self._updatecounter = 0
  1120.         self._turtles = []
  1121.         self.bgcolor('white')
  1122.         for btn in (1, 2, 3):
  1123.             self.onclick(None, btn)
  1124.         
  1125.         for key in self._keys[:]:
  1126.             self.onkey(None, key)
  1127.         
  1128.         Turtle._pen = None
  1129.  
  1130.     
  1131.     def mode(self, mode = None):
  1132.         """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
  1133.  
  1134.         Optional argument:
  1135.         mode -- on of the strings 'standard', 'logo' or 'world'
  1136.  
  1137.         Mode 'standard' is compatible with turtle.py.
  1138.         Mode 'logo' is compatible with most Logo-Turtle-Graphics.
  1139.         Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
  1140.         this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
  1141.         If mode is not given, return the current mode.
  1142.  
  1143.              Mode      Initial turtle heading     positive angles
  1144.          ------------|-------------------------|-------------------
  1145.           'standard'    to the right (east)       counterclockwise
  1146.             'logo'        upward    (north)         clockwise
  1147.  
  1148.         Examples:
  1149.         >>> mode('logo')   # resets turtle heading to north
  1150.         >>> mode()
  1151.         'logo'
  1152.         """
  1153.         if mode == None:
  1154.             return self._mode
  1155.         mode = mode.lower()
  1156.         if mode not in ('standard', 'logo', 'world'):
  1157.             raise TurtleGraphicsError('No turtle-graphics-mode %s' % mode)
  1158.         mode not in ('standard', 'logo', 'world')
  1159.         self._mode = mode
  1160.         self.reset()
  1161.  
  1162.     
  1163.     def setworldcoordinates(self, llx, lly, urx, ury):
  1164.         """Set up a user defined coordinate-system.
  1165.  
  1166.         Arguments:
  1167.         llx -- a number, x-coordinate of lower left corner of canvas
  1168.         lly -- a number, y-coordinate of lower left corner of canvas
  1169.         urx -- a number, x-coordinate of upper right corner of canvas
  1170.         ury -- a number, y-coordinate of upper right corner of canvas
  1171.  
  1172.         Set up user coodinat-system and switch to mode 'world' if necessary.
  1173.         This performs a screen.reset. If mode 'world' is already active,
  1174.         all drawings are redrawn according to the new coordinates.
  1175.  
  1176.         But ATTENTION: in user-defined coordinatesystems angles may appear
  1177.         distorted. (see Screen.mode())
  1178.  
  1179.         Example (for a TurtleScreen instance named screen):
  1180.         >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
  1181.         >>> for _ in range(36):
  1182.                 left(10)
  1183.                 forward(0.5)
  1184.         """
  1185.         if self.mode() != 'world':
  1186.             self.mode('world')
  1187.         
  1188.         xspan = float(urx - llx)
  1189.         yspan = float(ury - lly)
  1190.         (wx, wy) = self._window_size()
  1191.         self.screensize(wx - 20, wy - 20)
  1192.         oldxscale = self.xscale
  1193.         oldyscale = self.yscale
  1194.         self.xscale = self.canvwidth / xspan
  1195.         self.yscale = self.canvheight / yspan
  1196.         srx1 = llx * self.xscale
  1197.         sry1 = -ury * self.yscale
  1198.         srx2 = self.canvwidth + srx1
  1199.         sry2 = self.canvheight + sry1
  1200.         self._setscrollregion(srx1, sry1, srx2, sry2)
  1201.         self._rescale(self.xscale / oldxscale, self.yscale / oldyscale)
  1202.         self.update()
  1203.  
  1204.     
  1205.     def register_shape(self, name, shape = None):
  1206.         '''Adds a turtle shape to TurtleScreen\'s shapelist.
  1207.  
  1208.         Arguments:
  1209.         (1) name is the name of a gif-file and shape is None.
  1210.             Installs the corresponding image shape.
  1211.             !! Image-shapes DO NOT rotate when turning the turtle,
  1212.             !! so they do not display the heading of the turtle!
  1213.         (2) name is an arbitrary string and shape is a tuple
  1214.             of pairs of coordinates. Installs the corresponding
  1215.             polygon shape
  1216.         (3) name is an arbitrary string and shape is a
  1217.             (compound) Shape object. Installs the corresponding
  1218.             compound shape.
  1219.         To use a shape, you have to issue the command shape(shapename).
  1220.  
  1221.         call: register_shape("turtle.gif")
  1222.         --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
  1223.  
  1224.         Example (for a TurtleScreen instance named screen):
  1225.         >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
  1226.  
  1227.         '''
  1228.         if shape is None:
  1229.             if name.lower().endswith('.gif'):
  1230.                 shape = Shape('image', self._image(name))
  1231.             else:
  1232.                 raise TurtleGraphicsError('Bad arguments for register_shape.\n' + 'Use  help(register_shape)')
  1233.         name.lower().endswith('.gif')
  1234.         if isinstance(shape, tuple):
  1235.             shape = Shape('polygon', shape)
  1236.         
  1237.         self._shapes[name] = shape
  1238.  
  1239.     
  1240.     def _colorstr(self, color):
  1241.         """Return color string corresponding to args.
  1242.  
  1243.         Argument may be a string or a tuple of three
  1244.         numbers corresponding to actual colormode,
  1245.         i.e. in the range 0<=n<=colormode.
  1246.  
  1247.         If the argument doesn't represent a color,
  1248.         an error is raised.
  1249.         """
  1250.         if len(color) == 1:
  1251.             color = color[0]
  1252.         
  1253.         if isinstance(color, str):
  1254.             if self._iscolorstring(color) or color == '':
  1255.                 return color
  1256.             raise TurtleGraphicsError('bad color string: %s' % str(color))
  1257.         isinstance(color, str)
  1258.         
  1259.         try:
  1260.             (r, g, b) = color
  1261.         except:
  1262.             raise TurtleGraphicsError('bad color arguments: %s' % str(color))
  1263.  
  1264.         if r <= r:
  1265.             pass
  1266.         elif r <= 255:
  1267.             if g <= g:
  1268.                 pass
  1269.             elif g <= 255:
  1270.                 if b <= b:
  1271.                     pass
  1272.                 elif not b <= 255:
  1273.                     raise TurtleGraphicsError('bad color sequence: %s' % str(color))
  1274.                 
  1275.         return '#%02x%02x%02x' % (r, g, b)
  1276.  
  1277.     
  1278.     def _color(self, cstr):
  1279.         if not cstr.startswith('#'):
  1280.             return cstr
  1281.         if len(cstr) == 7:
  1282.             cl = [ int(cstr[i:i + 2], 16) for i in (1, 3, 5) ]
  1283.         elif len(cstr) == 4:
  1284.             cl = [ 16 * int(cstr[h], 16) for h in cstr[1:] ]
  1285.         else:
  1286.             raise TurtleGraphicsError('bad colorstring: %s' % cstr)
  1287.         return []([ c * self._colormode / 255 for c in cl ])
  1288.  
  1289.     
  1290.     def colormode(self, cmode = None):
  1291.         '''Return the colormode or set it to 1.0 or 255.
  1292.  
  1293.         Optional argument:
  1294.         cmode -- one of the values 1.0 or 255
  1295.  
  1296.         r, g, b values of colortriples have to be in range 0..cmode.
  1297.  
  1298.         Example (for a TurtleScreen instance named screen):
  1299.         >>> screen.colormode()
  1300.         1.0
  1301.         >>> screen.colormode(255)
  1302.         >>> turtle.pencolor(240,160,80)
  1303.         '''
  1304.         if cmode is None:
  1305.             return self._colormode
  1306.         if cmode == 1:
  1307.             self._colormode = float(cmode)
  1308.         elif cmode == 255:
  1309.             self._colormode = int(cmode)
  1310.         
  1311.  
  1312.     
  1313.     def reset(self):
  1314.         '''Reset all Turtles on the Screen to their initial state.
  1315.  
  1316.         No argument.
  1317.  
  1318.         Example (for a TurtleScreen instance named screen):
  1319.         >>> screen.reset()
  1320.         '''
  1321.         for turtle in self._turtles:
  1322.             turtle._setmode(self._mode)
  1323.             turtle.reset()
  1324.         
  1325.  
  1326.     
  1327.     def turtles(self):
  1328.         '''Return the list of turtles on the screen.
  1329.  
  1330.         Example (for a TurtleScreen instance named screen):
  1331.         >>> screen.turtles()
  1332.         [<turtle.Turtle object at 0x00E11FB0>]
  1333.         '''
  1334.         return self._turtles
  1335.  
  1336.     
  1337.     def bgcolor(self, *args):
  1338.         '''Set or return backgroundcolor of the TurtleScreen.
  1339.  
  1340.         Arguments (if given): a color string or three numbers
  1341.         in the range 0..colormode or a 3-tuple of such numbers.
  1342.  
  1343.         Example (for a TurtleScreen instance named screen):
  1344.         >>> screen.bgcolor("orange")
  1345.         >>> screen.bgcolor()
  1346.         \'orange\'
  1347.         >>> screen.bgcolor(0.5,0,0.5)
  1348.         >>> screen.bgcolor()
  1349.         \'#800080\'
  1350.         '''
  1351.         if args:
  1352.             color = self._colorstr(args)
  1353.         else:
  1354.             color = None
  1355.         color = self._bgcolor(color)
  1356.         if color is not None:
  1357.             color = self._color(color)
  1358.         
  1359.         return color
  1360.  
  1361.     
  1362.     def tracer(self, n = None, delay = None):
  1363.         '''Turns turtle animation on/off and set delay for update drawings.
  1364.  
  1365.         Optional arguments:
  1366.         n -- nonnegative  integer
  1367.         delay -- nonnegative  integer
  1368.  
  1369.         If n is given, only each n-th regular screen update is really performed.
  1370.         (Can be used to accelerate the drawing of complex graphics.)
  1371.         Second arguments sets delay value (see RawTurtle.delay())
  1372.  
  1373.         Example (for a TurtleScreen instance named screen):
  1374.         >>> screen.tracer(8, 25)
  1375.         >>> dist = 2
  1376.         >>> for i in range(200):
  1377.                 fd(dist)
  1378.                 rt(90)
  1379.                 dist += 2
  1380.         '''
  1381.         if n is None:
  1382.             return self._tracing
  1383.         self._tracing = int(n)
  1384.         self._updatecounter = 0
  1385.         if delay is not None:
  1386.             self._delayvalue = int(delay)
  1387.         
  1388.         if self._tracing:
  1389.             self.update()
  1390.         
  1391.  
  1392.     
  1393.     def delay(self, delay = None):
  1394.         ''' Return or set the drawing delay in milliseconds.
  1395.  
  1396.         Optional argument:
  1397.         delay -- positive integer
  1398.  
  1399.         Example (for a TurtleScreen instance named screen):
  1400.         >>> screen.delay(15)
  1401.         >>> screen.delay()
  1402.         15
  1403.         '''
  1404.         if delay is None:
  1405.             return self._delayvalue
  1406.         self._delayvalue = int(delay)
  1407.  
  1408.     
  1409.     def _incrementudc(self):
  1410.         '''Increment upadate counter.'''
  1411.         if not TurtleScreen._RUNNING:
  1412.             TurtleScreen._RUNNNING = True
  1413.             raise Terminator
  1414.         TurtleScreen._RUNNING
  1415.  
  1416.     
  1417.     def update(self):
  1418.         '''Perform a TurtleScreen update.
  1419.         '''
  1420.         tracing = self._tracing
  1421.         self._tracing = True
  1422.         for t in self.turtles():
  1423.             t._update_data()
  1424.             t._drawturtle()
  1425.         
  1426.         self._tracing = tracing
  1427.         self._update()
  1428.  
  1429.     
  1430.     def window_width(self):
  1431.         ''' Return the width of the turtle window.
  1432.  
  1433.         Example (for a TurtleScreen instance named screen):
  1434.         >>> screen.window_width()
  1435.         640
  1436.         '''
  1437.         return self._window_size()[0]
  1438.  
  1439.     
  1440.     def window_height(self):
  1441.         ''' Return the height of the turtle window.
  1442.  
  1443.         Example (for a TurtleScreen instance named screen):
  1444.         >>> screen.window_height()
  1445.         480
  1446.         '''
  1447.         return self._window_size()[1]
  1448.  
  1449.     
  1450.     def getcanvas(self):
  1451.         '''Return the Canvas of this TurtleScreen.
  1452.  
  1453.         No argument.
  1454.  
  1455.         Example (for a Screen instance named screen):
  1456.         >>> cv = screen.getcanvas()
  1457.         >>> cv
  1458.         <turtle.ScrolledCanvas instance at 0x010742D8>
  1459.         '''
  1460.         return self.cv
  1461.  
  1462.     
  1463.     def getshapes(self):
  1464.         """Return a list of names of all currently available turtle shapes.
  1465.  
  1466.         No argument.
  1467.  
  1468.         Example (for a TurtleScreen instance named screen):
  1469.         >>> screen.getshapes()
  1470.         ['arrow', 'blank', 'circle', ... , 'turtle']
  1471.         """
  1472.         return sorted(self._shapes.keys())
  1473.  
  1474.     
  1475.     def onclick(self, fun, btn = 1, add = None):
  1476.         '''Bind fun to mouse-click event on canvas.
  1477.  
  1478.         Arguments:
  1479.         fun -- a function with two arguments, the coordinates of the
  1480.                clicked point on the canvas.
  1481.         num -- the number of the mouse-button, defaults to 1
  1482.  
  1483.         Example (for a TurtleScreen instance named screen
  1484.         and a Turtle instance named turtle):
  1485.  
  1486.         >>> screen.onclick(turtle.goto)
  1487.  
  1488.         ### Subsequently clicking into the TurtleScreen will
  1489.         ### make the turtle move to the clicked point.
  1490.         >>> screen.onclick(None)
  1491.  
  1492.         ### event-binding will be removed
  1493.         '''
  1494.         self._onscreenclick(fun, btn, add)
  1495.  
  1496.     
  1497.     def onkey(self, fun, key):
  1498.         '''Bind fun to key-release event of key.
  1499.  
  1500.         Arguments:
  1501.         fun -- a function with no arguments
  1502.         key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
  1503.  
  1504.         In order to be able to register key-events, TurtleScreen
  1505.         must have focus. (See method listen.)
  1506.  
  1507.         Example (for a TurtleScreen instance named screen
  1508.         and a Turtle instance named turtle):
  1509.  
  1510.         >>> def f():
  1511.                 fd(50)
  1512.                 lt(60)
  1513.  
  1514.  
  1515.         >>> screen.onkey(f, "Up")
  1516.         >>> screen.listen()
  1517.  
  1518.         ### Subsequently the turtle can be moved by
  1519.         ### repeatedly pressing the up-arrow key,
  1520.         ### consequently drawing a hexagon
  1521.         '''
  1522.         if fun == None:
  1523.             if key in self._keys:
  1524.                 self._keys.remove(key)
  1525.             
  1526.         elif key not in self._keys:
  1527.             self._keys.append(key)
  1528.         
  1529.         self._onkey(fun, key)
  1530.  
  1531.     
  1532.     def listen(self, xdummy = None, ydummy = None):
  1533.         '''Set focus on TurtleScreen (in order to collect key-events)
  1534.  
  1535.         No arguments.
  1536.         Dummy arguments are provided in order
  1537.         to be able to pass listen to the onclick method.
  1538.  
  1539.         Example (for a TurtleScreen instance named screen):
  1540.         >>> screen.listen()
  1541.         '''
  1542.         self._listen()
  1543.  
  1544.     
  1545.     def ontimer(self, fun, t = 0):
  1546.         '''Install a timer, which calls fun after t milliseconds.
  1547.  
  1548.         Arguments:
  1549.         fun -- a function with no arguments.
  1550.         t -- a number >= 0
  1551.  
  1552.         Example (for a TurtleScreen instance named screen):
  1553.  
  1554.         >>> running = True
  1555.         >>> def f():
  1556.                 if running:
  1557.                         fd(50)
  1558.                         lt(60)
  1559.                         screen.ontimer(f, 250)
  1560.  
  1561.         >>> f()   ### makes the turtle marching around
  1562.         >>> running = False
  1563.         '''
  1564.         self._ontimer(fun, t)
  1565.  
  1566.     
  1567.     def bgpic(self, picname = None):
  1568.         '''Set background image or return name of current backgroundimage.
  1569.  
  1570.         Optional argument:
  1571.         picname -- a string, name of a gif-file or "nopic".
  1572.  
  1573.         If picname is a filename, set the corresponing image as background.
  1574.         If picname is "nopic", delete backgroundimage, if present.
  1575.         If picname is None, return the filename of the current backgroundimage.
  1576.  
  1577.         Example (for a TurtleScreen instance named screen):
  1578.         >>> screen.bgpic()
  1579.         \'nopic\'
  1580.         >>> screen.bgpic("landscape.gif")
  1581.         >>> screen.bgpic()
  1582.         \'landscape.gif\'
  1583.         '''
  1584.         if picname is None:
  1585.             return self._bgpicname
  1586.         if picname not in self._bgpics:
  1587.             self._bgpics[picname] = self._image(picname)
  1588.         
  1589.         self._setbgpic(self._bgpic, self._bgpics[picname])
  1590.         self._bgpicname = picname
  1591.  
  1592.     
  1593.     def screensize(self, canvwidth = None, canvheight = None, bg = None):
  1594.         '''Resize the canvas the turtles are drawing on.
  1595.  
  1596.         Optional arguments:
  1597.         canvwidth -- positive integer, new width of canvas in pixels
  1598.         canvheight --  positive integer, new height of canvas in pixels
  1599.         bg -- colorstring or color-tupel, new backgroundcolor
  1600.         If no arguments are given, return current (canvaswidth, canvasheight)
  1601.  
  1602.         Do not alter the drawing window. To observe hidden parts of
  1603.         the canvas use the scrollbars. (Can make visible those parts
  1604.         of a drawing, which were outside the canvas before!)
  1605.  
  1606.         Example (for a Turtle instance named turtle):
  1607.         >>> turtle.screensize(2000,1500)
  1608.             ### e. g. to search for an erroneously escaped turtle ;-)
  1609.         '''
  1610.         return self._resize(canvwidth, canvheight, bg)
  1611.  
  1612.     onscreenclick = onclick
  1613.     resetscreen = reset
  1614.     clearscreen = clear
  1615.     addshape = register_shape
  1616.  
  1617.  
  1618. class TNavigator(object):
  1619.     '''Navigation part of the RawTurtle.
  1620.     Implements methods for turtle movement.
  1621.     '''
  1622.     START_ORIENTATION = {
  1623.         'standard': Vec2D(1, 0),
  1624.         'world': Vec2D(1, 0),
  1625.         'logo': Vec2D(0, 1) }
  1626.     DEFAULT_MODE = 'standard'
  1627.     DEFAULT_ANGLEOFFSET = 0
  1628.     DEFAULT_ANGLEORIENT = 1
  1629.     
  1630.     def __init__(self, mode = DEFAULT_MODE):
  1631.         self._angleOffset = self.DEFAULT_ANGLEOFFSET
  1632.         self._angleOrient = self.DEFAULT_ANGLEORIENT
  1633.         self._mode = mode
  1634.         self.undobuffer = None
  1635.         self.degrees()
  1636.         self._mode = None
  1637.         self._setmode(mode)
  1638.         TNavigator.reset(self)
  1639.  
  1640.     
  1641.     def reset(self):
  1642.         '''reset turtle to its initial values
  1643.  
  1644.         Will be overwritten by parent class
  1645.         '''
  1646.         self._position = Vec2D(0, 0)
  1647.         self._orient = TNavigator.START_ORIENTATION[self._mode]
  1648.  
  1649.     
  1650.     def _setmode(self, mode = None):
  1651.         """Set turtle-mode to 'standard', 'world' or 'logo'.
  1652.         """
  1653.         if mode == None:
  1654.             return self._mode
  1655.         if mode not in ('standard', 'logo', 'world'):
  1656.             return None
  1657.         self._mode = mode
  1658.  
  1659.     
  1660.     def _setDegreesPerAU(self, fullcircle):
  1661.         '''Helper function for degrees() and radians()'''
  1662.         self._fullcircle = fullcircle
  1663.         self._degreesPerAU = 360 / fullcircle
  1664.         if self._mode == 'standard':
  1665.             self._angleOffset = 0
  1666.         else:
  1667.             self._angleOffset = fullcircle / 4
  1668.  
  1669.     
  1670.     def degrees(self, fullcircle = 360):
  1671.         """ Set angle measurement units to degrees.
  1672.  
  1673.         Optional argument:
  1674.         fullcircle -  a number
  1675.  
  1676.         Set angle measurement units, i. e. set number
  1677.         of 'degrees' for a full circle. Dafault value is
  1678.         360 degrees.
  1679.  
  1680.         Example (for a Turtle instance named turtle):
  1681.         >>> turtle.left(90)
  1682.         >>> turtle.heading()
  1683.         90
  1684.         >>> turtle.degrees(400.0)  # angle measurement in gon
  1685.         >>> turtle.heading()
  1686.         100
  1687.  
  1688.         """
  1689.         self._setDegreesPerAU(fullcircle)
  1690.  
  1691.     
  1692.     def radians(self):
  1693.         ''' Set the angle measurement units to radians.
  1694.  
  1695.         No arguments.
  1696.  
  1697.         Example (for a Turtle instance named turtle):
  1698.         >>> turtle.heading()
  1699.         90
  1700.         >>> turtle.radians()
  1701.         >>> turtle.heading()
  1702.         1.5707963267948966
  1703.         '''
  1704.         self._setDegreesPerAU(2 * math.pi)
  1705.  
  1706.     
  1707.     def _go(self, distance):
  1708.         '''move turtle forward by specified distance'''
  1709.         ende = self._position + self._orient * distance
  1710.         self._goto(ende)
  1711.  
  1712.     
  1713.     def _rotate(self, angle):
  1714.         '''Turn turtle counterclockwise by specified angle if angle > 0.'''
  1715.         angle *= self._degreesPerAU
  1716.         self._orient = self._orient.rotate(angle)
  1717.  
  1718.     
  1719.     def _goto(self, end):
  1720.         '''move turtle to position end.'''
  1721.         self._position = end
  1722.  
  1723.     
  1724.     def forward(self, distance):
  1725.         '''Move the turtle forward by the specified distance.
  1726.  
  1727.         Aliases: forward | fd
  1728.  
  1729.         Argument:
  1730.         distance -- a number (integer or float)
  1731.  
  1732.         Move the turtle forward by the specified distance, in the direction
  1733.         the turtle is headed.
  1734.  
  1735.         Example (for a Turtle instance named turtle):
  1736.         >>> turtle.position()
  1737.         (0.00, 0.00)
  1738.         >>> turtle.forward(25)
  1739.         >>> turtle.position()
  1740.         (25.00,0.00)
  1741.         >>> turtle.forward(-75)
  1742.         >>> turtle.position()
  1743.         (-50.00,0.00)
  1744.         '''
  1745.         self._go(distance)
  1746.  
  1747.     
  1748.     def back(self, distance):
  1749.         """Move the turtle backward by distance.
  1750.  
  1751.         Aliases: back | backward | bk
  1752.  
  1753.         Argument:
  1754.         distance -- a number
  1755.  
  1756.         Move the turtle backward by distance ,opposite to the direction the
  1757.         turtle is headed. Do not change the turtle's heading.
  1758.  
  1759.         Example (for a Turtle instance named turtle):
  1760.         >>> turtle.position()
  1761.         (0.00, 0.00)
  1762.         >>> turtle.backward(30)
  1763.         >>> turtle.position()
  1764.         (-30.00, 0.00)
  1765.         """
  1766.         self._go(-distance)
  1767.  
  1768.     
  1769.     def right(self, angle):
  1770.         '''Turn turtle right by angle units.
  1771.  
  1772.         Aliases: right | rt
  1773.  
  1774.         Argument:
  1775.         angle -- a number (integer or float)
  1776.  
  1777.         Turn turtle right by angle units. (Units are by default degrees,
  1778.         but can be set via the degrees() and radians() functions.)
  1779.         Angle orientation depends on mode. (See this.)
  1780.  
  1781.         Example (for a Turtle instance named turtle):
  1782.         >>> turtle.heading()
  1783.         22.0
  1784.         >>> turtle.right(45)
  1785.         >>> turtle.heading()
  1786.         337.0
  1787.         '''
  1788.         self._rotate(-angle)
  1789.  
  1790.     
  1791.     def left(self, angle):
  1792.         '''Turn turtle left by angle units.
  1793.  
  1794.         Aliases: left | lt
  1795.  
  1796.         Argument:
  1797.         angle -- a number (integer or float)
  1798.  
  1799.         Turn turtle left by angle units. (Units are by default degrees,
  1800.         but can be set via the degrees() and radians() functions.)
  1801.         Angle orientation depends on mode. (See this.)
  1802.  
  1803.         Example (for a Turtle instance named turtle):
  1804.         >>> turtle.heading()
  1805.         22.0
  1806.         >>> turtle.left(45)
  1807.         >>> turtle.heading()
  1808.         67.0
  1809.         '''
  1810.         self._rotate(angle)
  1811.  
  1812.     
  1813.     def pos(self):
  1814.         """Return the turtle's current location (x,y), as a Vec2D-vector.
  1815.  
  1816.         Aliases: pos | position
  1817.  
  1818.         No arguments.
  1819.  
  1820.         Example (for a Turtle instance named turtle):
  1821.         >>> turtle.pos()
  1822.         (0.00, 240.00)
  1823.         """
  1824.         return self._position
  1825.  
  1826.     
  1827.     def xcor(self):
  1828.         """ Return the turtle's x coordinate.
  1829.  
  1830.         No arguments.
  1831.  
  1832.         Example (for a Turtle instance named turtle):
  1833.         >>> reset()
  1834.         >>> turtle.left(60)
  1835.         >>> turtle.forward(100)
  1836.         >>> print turtle.xcor()
  1837.         50.0
  1838.         """
  1839.         return self._position[0]
  1840.  
  1841.     
  1842.     def ycor(self):
  1843.         """ Return the turtle's y coordinate
  1844.         ---
  1845.         No arguments.
  1846.  
  1847.         Example (for a Turtle instance named turtle):
  1848.         >>> reset()
  1849.         >>> turtle.left(60)
  1850.         >>> turtle.forward(100)
  1851.         >>> print turtle.ycor()
  1852.         86.6025403784
  1853.         """
  1854.         return self._position[1]
  1855.  
  1856.     
  1857.     def goto(self, x, y = None):
  1858.         """Move turtle to an absolute position.
  1859.  
  1860.         Aliases: setpos | setposition | goto:
  1861.  
  1862.         Arguments:
  1863.         x -- a number      or     a pair/vector of numbers
  1864.         y -- a number             None
  1865.  
  1866.         call: goto(x, y)         # two coordinates
  1867.         --or: goto((x, y))       # a pair (tuple) of coordinates
  1868.         --or: goto(vec)          # e.g. as returned by pos()
  1869.  
  1870.         Move turtle to an absolute position. If the pen is down,
  1871.         a line will be drawn. The turtle's orientation does not change.
  1872.  
  1873.         Example (for a Turtle instance named turtle):
  1874.         >>> tp = turtle.pos()
  1875.         >>> tp
  1876.         (0.00, 0.00)
  1877.         >>> turtle.setpos(60,30)
  1878.         >>> turtle.pos()
  1879.         (60.00,30.00)
  1880.         >>> turtle.setpos((20,80))
  1881.         >>> turtle.pos()
  1882.         (20.00,80.00)
  1883.         >>> turtle.setpos(tp)
  1884.         >>> turtle.pos()
  1885.         (0.00,0.00)
  1886.         """
  1887.         if y is None:
  1888.             self._goto(Vec2D(*x))
  1889.         else:
  1890.             self._goto(Vec2D(x, y))
  1891.  
  1892.     
  1893.     def home(self):
  1894.         '''Move turtle to the origin - coordinates (0,0).
  1895.  
  1896.         No arguments.
  1897.  
  1898.         Move turtle to the origin - coordinates (0,0) and set its
  1899.         heading to its start-orientation (which depends on mode).
  1900.  
  1901.         Example (for a Turtle instance named turtle):
  1902.         >>> turtle.home()
  1903.         '''
  1904.         self.goto(0, 0)
  1905.         self.setheading(0)
  1906.  
  1907.     
  1908.     def setx(self, x):
  1909.         """Set the turtle's first coordinate to x
  1910.  
  1911.         Argument:
  1912.         x -- a number (integer or float)
  1913.  
  1914.         Set the turtle's first coordinate to x, leave second coordinate
  1915.         unchanged.
  1916.  
  1917.         Example (for a Turtle instance named turtle):
  1918.         >>> turtle.position()
  1919.         (0.00, 240.00)
  1920.         >>> turtle.setx(10)
  1921.         >>> turtle.position()
  1922.         (10.00, 240.00)
  1923.         """
  1924.         self._goto(Vec2D(x, self._position[1]))
  1925.  
  1926.     
  1927.     def sety(self, y):
  1928.         """Set the turtle's second coordinate to y
  1929.  
  1930.         Argument:
  1931.         y -- a number (integer or float)
  1932.  
  1933.         Set the turtle's first coordinate to x, second coordinate remains
  1934.         unchanged.
  1935.  
  1936.         Example (for a Turtle instance named turtle):
  1937.         >>> turtle.position()
  1938.         (0.00, 40.00)
  1939.         >>> turtle.sety(-10)
  1940.         >>> turtle.position()
  1941.         (0.00, -10.00)
  1942.         """
  1943.         self._goto(Vec2D(self._position[0], y))
  1944.  
  1945.     
  1946.     def distance(self, x, y = None):
  1947.         '''Return the distance from the turtle to (x,y) in turtle step units.
  1948.  
  1949.         Arguments:
  1950.         x -- a number   or  a pair/vector of numbers   or   a turtle instance
  1951.         y -- a number       None                            None
  1952.  
  1953.         call: distance(x, y)         # two coordinates
  1954.         --or: distance((x, y))       # a pair (tuple) of coordinates
  1955.         --or: distance(vec)          # e.g. as returned by pos()
  1956.         --or: distance(mypen)        # where mypen is another turtle
  1957.  
  1958.         Example (for a Turtle instance named turtle):
  1959.         >>> turtle.pos()
  1960.         (0.00, 0.00)
  1961.         >>> turtle.distance(30,40)
  1962.         50.0
  1963.         >>> pen = Turtle()
  1964.         >>> pen.forward(77)
  1965.         >>> turtle.distance(pen)
  1966.         77.0
  1967.         '''
  1968.         if y is not None:
  1969.             pos = Vec2D(x, y)
  1970.         
  1971.         if isinstance(x, Vec2D):
  1972.             pos = x
  1973.         elif isinstance(x, tuple):
  1974.             pos = Vec2D(*x)
  1975.         elif isinstance(x, TNavigator):
  1976.             pos = x._position
  1977.         
  1978.         return abs(pos - self._position)
  1979.  
  1980.     
  1981.     def towards(self, x, y = None):
  1982.         '''Return the angle of the line from the turtle\'s position to (x, y).
  1983.  
  1984.         Arguments:
  1985.         x -- a number   or  a pair/vector of numbers   or   a turtle instance
  1986.         y -- a number       None                            None
  1987.  
  1988.         call: distance(x, y)         # two coordinates
  1989.         --or: distance((x, y))       # a pair (tuple) of coordinates
  1990.         --or: distance(vec)          # e.g. as returned by pos()
  1991.         --or: distance(mypen)        # where mypen is another turtle
  1992.  
  1993.         Return the angle, between the line from turtle-position to position
  1994.         specified by x, y and the turtle\'s start orientation. (Depends on
  1995.         modes - "standard" or "logo")
  1996.  
  1997.         Example (for a Turtle instance named turtle):
  1998.         >>> turtle.pos()
  1999.         (10.00, 10.00)
  2000.         >>> turtle.towards(0,0)
  2001.         225.0
  2002.         '''
  2003.         if y is not None:
  2004.             pos = Vec2D(x, y)
  2005.         
  2006.         if isinstance(x, Vec2D):
  2007.             pos = x
  2008.         elif isinstance(x, tuple):
  2009.             pos = Vec2D(*x)
  2010.         elif isinstance(x, TNavigator):
  2011.             pos = x._position
  2012.         
  2013.         (x, y) = pos - self._position
  2014.         result = round(math.atan2(y, x) * 180 / math.pi, 10) % 360
  2015.         result /= self._degreesPerAU
  2016.         return (self._angleOffset + self._angleOrient * result) % self._fullcircle
  2017.  
  2018.     
  2019.     def heading(self):
  2020.         """ Return the turtle's current heading.
  2021.  
  2022.         No arguments.
  2023.  
  2024.         Example (for a Turtle instance named turtle):
  2025.         >>> turtle.left(67)
  2026.         >>> turtle.heading()
  2027.         67.0
  2028.         """
  2029.         (x, y) = self._orient
  2030.         result = round(math.atan2(y, x) * 180 / math.pi, 10) % 360
  2031.         result /= self._degreesPerAU
  2032.         return (self._angleOffset + self._angleOrient * result) % self._fullcircle
  2033.  
  2034.     
  2035.     def setheading(self, to_angle):
  2036.         '''Set the orientation of the turtle to to_angle.
  2037.  
  2038.         Aliases:  setheading | seth
  2039.  
  2040.         Argument:
  2041.         to_angle -- a number (integer or float)
  2042.  
  2043.         Set the orientation of the turtle to to_angle.
  2044.         Here are some common directions in degrees:
  2045.  
  2046.          standard - mode:          logo-mode:
  2047.         -------------------|--------------------
  2048.            0 - east                0 - north
  2049.           90 - north              90 - east
  2050.          180 - west              180 - south
  2051.          270 - south             270 - west
  2052.  
  2053.         Example (for a Turtle instance named turtle):
  2054.         >>> turtle.setheading(90)
  2055.         >>> turtle.heading()
  2056.         90
  2057.         '''
  2058.         angle = (to_angle - self.heading()) * self._angleOrient
  2059.         full = self._fullcircle
  2060.         angle = (angle + full / 2) % full - full / 2
  2061.         self._rotate(angle)
  2062.  
  2063.     
  2064.     def circle(self, radius, extent = None, steps = None):
  2065.         ''' Draw a circle with given radius.
  2066.  
  2067.         Arguments:
  2068.         radius -- a number
  2069.         extent (optional) -- a number
  2070.         steps (optional) -- an integer
  2071.  
  2072.         Draw a circle with given radius. The center is radius units left
  2073.         of the turtle; extent - an angle - determines which part of the
  2074.         circle is drawn. If extent is not given, draw the entire circle.
  2075.         If extent is not a full circle, one endpoint of the arc is the
  2076.         current pen position. Draw the arc in counterclockwise direction
  2077.         if radius is positive, otherwise in clockwise direction. Finally
  2078.         the direction of the turtle is changed by the amount of extent.
  2079.  
  2080.         As the circle is approximated by an inscribed regular polygon,
  2081.         steps determines the number of steps to use. If not given,
  2082.         it will be calculated automatically. Maybe used to draw regular
  2083.         polygons.
  2084.  
  2085.         call: circle(radius)                  # full circle
  2086.         --or: circle(radius, extent)          # arc
  2087.         --or: circle(radius, extent, steps)
  2088.         --or: circle(radius, steps=6)         # 6-sided polygon
  2089.  
  2090.         Example (for a Turtle instance named turtle):
  2091.         >>> turtle.circle(50)
  2092.         >>> turtle.circle(120, 180)  # semicircle
  2093.         '''
  2094.         if self.undobuffer:
  2095.             self.undobuffer.push([
  2096.                 'seq'])
  2097.             self.undobuffer.cumulate = True
  2098.         
  2099.         speed = self.speed()
  2100.         if extent is None:
  2101.             extent = self._fullcircle
  2102.         
  2103.         if steps is None:
  2104.             frac = abs(extent) / self._fullcircle
  2105.             steps = 1 + int(min(11 + abs(radius) / 6, 59) * frac)
  2106.         
  2107.         w = 1 * extent / steps
  2108.         w2 = 0.5 * w
  2109.         l = 2 * radius * math.sin((w2 * math.pi / 180) * self._degreesPerAU)
  2110.         if radius < 0:
  2111.             l = -l
  2112.             w = -w
  2113.             w2 = -w2
  2114.         
  2115.         tr = self.tracer()
  2116.         dl = self._delay()
  2117.         if speed == 0:
  2118.             self.tracer(0, 0)
  2119.         else:
  2120.             self.speed(0)
  2121.         self._rotate(w2)
  2122.         for i in range(steps):
  2123.             self.speed(speed)
  2124.             self._go(l)
  2125.             self.speed(0)
  2126.             self._rotate(w)
  2127.         
  2128.         self._rotate(-w2)
  2129.         if speed == 0:
  2130.             self.tracer(tr, dl)
  2131.         
  2132.         self.speed(speed)
  2133.         if self.undobuffer:
  2134.             self.undobuffer.cumulate = False
  2135.         
  2136.  
  2137.     
  2138.     def speed(self, s = 0):
  2139.         '''dummy method - to be overwritten by child class'''
  2140.         pass
  2141.  
  2142.     
  2143.     def tracer(self, a = None, b = None):
  2144.         '''dummy method - to be overwritten by child class'''
  2145.         pass
  2146.  
  2147.     
  2148.     def _delay(self, n = None):
  2149.         '''dummy method - to be overwritten by child class'''
  2150.         pass
  2151.  
  2152.     fd = forward
  2153.     bk = back
  2154.     backward = back
  2155.     rt = right
  2156.     lt = left
  2157.     position = pos
  2158.     setpos = goto
  2159.     setposition = goto
  2160.     seth = setheading
  2161.  
  2162.  
  2163. class TPen(object):
  2164.     '''Drawing part of the RawTurtle.
  2165.     Implements drawing properties.
  2166.     '''
  2167.     
  2168.     def __init__(self, resizemode = _CFG['resizemode']):
  2169.         self._resizemode = resizemode
  2170.         self.undobuffer = None
  2171.         TPen._reset(self)
  2172.  
  2173.     
  2174.     def _reset(self, pencolor = _CFG['pencolor'], fillcolor = _CFG['fillcolor']):
  2175.         self._pensize = 1
  2176.         self._shown = True
  2177.         self._pencolor = pencolor
  2178.         self._fillcolor = fillcolor
  2179.         self._drawing = True
  2180.         self._speed = 3
  2181.         self._stretchfactor = (1, 1)
  2182.         self._tilt = 0
  2183.         self._outlinewidth = 1
  2184.  
  2185.     
  2186.     def resizemode(self, rmode = None):
  2187.         '''Set resizemode to one of the values: "auto", "user", "noresize".
  2188.  
  2189.         (Optional) Argument:
  2190.         rmode -- one of the strings "auto", "user", "noresize"
  2191.  
  2192.         Different resizemodes have the following effects:
  2193.           - "auto" adapts the appearance of the turtle
  2194.                    corresponding to the value of pensize.
  2195.           - "user" adapts the appearance of the turtle according to the
  2196.                    values of stretchfactor and outlinewidth (outline),
  2197.                    which are set by shapesize()
  2198.           - "noresize" no adaption of the turtle\'s appearance takes place.
  2199.         If no argument is given, return current resizemode.
  2200.         resizemode("user") is called by a call of shapesize with arguments.
  2201.  
  2202.  
  2203.         Examples (for a Turtle instance named turtle):
  2204.         >>> turtle.resizemode("noresize")
  2205.         >>> turtle.resizemode()
  2206.         \'noresize\'
  2207.         '''
  2208.         if rmode is None:
  2209.             return self._resizemode
  2210.         rmode = rmode.lower()
  2211.         if rmode in ('auto', 'user', 'noresize'):
  2212.             self.pen(resizemode = rmode)
  2213.         
  2214.  
  2215.     
  2216.     def pensize(self, width = None):
  2217.         '''Set or return the line thickness.
  2218.  
  2219.         Aliases:  pensize | width
  2220.  
  2221.         Argument:
  2222.         width -- positive number
  2223.  
  2224.         Set the line thickness to width or return it. If resizemode is set
  2225.         to "auto" and turtleshape is a polygon, that polygon is drawn with
  2226.         the same line thickness. If no argument is given, current pensize
  2227.         is returned.
  2228.  
  2229.         Example (for a Turtle instance named turtle):
  2230.         >>> turtle.pensize()
  2231.         1
  2232.         turtle.pensize(10)   # from here on lines of width 10 are drawn
  2233.         '''
  2234.         if width is None:
  2235.             return self._pensize
  2236.         self.pen(pensize = width)
  2237.  
  2238.     
  2239.     def penup(self):
  2240.         '''Pull the pen up -- no drawing when moving.
  2241.  
  2242.         Aliases: penup | pu | up
  2243.  
  2244.         No argument
  2245.  
  2246.         Example (for a Turtle instance named turtle):
  2247.         >>> turtle.penup()
  2248.         '''
  2249.         if not self._drawing:
  2250.             return None
  2251.         self.pen(pendown = False)
  2252.  
  2253.     
  2254.     def pendown(self):
  2255.         '''Pull the pen down -- drawing when moving.
  2256.  
  2257.         Aliases: pendown | pd | down
  2258.  
  2259.         No argument.
  2260.  
  2261.         Example (for a Turtle instance named turtle):
  2262.         >>> turtle.pendown()
  2263.         '''
  2264.         if self._drawing:
  2265.             return None
  2266.         self.pen(pendown = True)
  2267.  
  2268.     
  2269.     def isdown(self):
  2270.         """Return True if pen is down, False if it's up.
  2271.  
  2272.         No argument.
  2273.  
  2274.         Example (for a Turtle instance named turtle):
  2275.         >>> turtle.penup()
  2276.         >>> turtle.isdown()
  2277.         False
  2278.         >>> turtle.pendown()
  2279.         >>> turtle.isdown()
  2280.         True
  2281.         """
  2282.         return self._drawing
  2283.  
  2284.     
  2285.     def speed(self, speed = None):
  2286.         """ Return or set the turtle's speed.
  2287.  
  2288.         Optional argument:
  2289.         speed -- an integer in the range 0..10 or a speedstring (see below)
  2290.  
  2291.         Set the turtle's speed to an integer value in the range 0 .. 10.
  2292.         If no argument is given: return current speed.
  2293.  
  2294.         If input is a number greater than 10 or smaller than 0.5,
  2295.         speed is set to 0.
  2296.         Speedstrings  are mapped to speedvalues in the following way:
  2297.             'fastest' :  0
  2298.             'fast'    :  10
  2299.             'normal'  :  6
  2300.             'slow'    :  3
  2301.             'slowest' :  1
  2302.         speeds from 1 to 10 enforce increasingly faster animation of
  2303.         line drawing and turtle turning.
  2304.  
  2305.         Attention:
  2306.         speed = 0 : *no* animation takes place. forward/back makes turtle jump
  2307.         and likewise left/right make the turtle turn instantly.
  2308.  
  2309.         Example (for a Turtle instance named turtle):
  2310.         >>> turtle.speed(3)
  2311.         """
  2312.         speeds = {
  2313.             'fastest': 0,
  2314.             'fast': 10,
  2315.             'normal': 6,
  2316.             'slow': 3,
  2317.             'slowest': 1 }
  2318.         if speed is None:
  2319.             return self._speed
  2320.         if speed in speeds:
  2321.             speed = speeds[speed]
  2322.         elif speed < speed:
  2323.             pass
  2324.         elif speed < 10.5:
  2325.             speed = int(round(speed))
  2326.         else:
  2327.             speed = 0
  2328.         self.pen(speed = speed)
  2329.  
  2330.     
  2331.     def color(self, *args):
  2332.         """Return or set the pencolor and fillcolor.
  2333.  
  2334.         Arguments:
  2335.         Several input formats are allowed.
  2336.         They use 0, 1, 2, or 3 arguments as follows:
  2337.  
  2338.         color()
  2339.             Return the current pencolor and the current fillcolor
  2340.             as a pair of color specification strings as are returned
  2341.             by pencolor and fillcolor.
  2342.         color(colorstring), color((r,g,b)), color(r,g,b)
  2343.             inputs as in pencolor, set both, fillcolor and pencolor,
  2344.             to the given value.
  2345.         color(colorstring1, colorstring2),
  2346.         color((r1,g1,b1), (r2,g2,b2))
  2347.             equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
  2348.             and analogously, if the other input format is used.
  2349.  
  2350.         If turtleshape is a polygon, outline and interior of that polygon
  2351.         is drawn with the newly set colors.
  2352.         For mor info see: pencolor, fillcolor
  2353.  
  2354.         Example (for a Turtle instance named turtle):
  2355.         >>> turtle.color('red', 'green')
  2356.         >>> turtle.color()
  2357.         ('red', 'green')
  2358.         >>> colormode(255)
  2359.         >>> color((40, 80, 120), (160, 200, 240))
  2360.         >>> color()
  2361.         ('#285078', '#a0c8f0')
  2362.         """
  2363.         if args:
  2364.             l = len(args)
  2365.             if l == 1:
  2366.                 pcolor = fcolor = args[0]
  2367.             elif l == 2:
  2368.                 (pcolor, fcolor) = args
  2369.             elif l == 3:
  2370.                 pcolor = fcolor = args
  2371.             
  2372.             pcolor = self._colorstr(pcolor)
  2373.             fcolor = self._colorstr(fcolor)
  2374.             self.pen(pencolor = pcolor, fillcolor = fcolor)
  2375.         else:
  2376.             return (self._color(self._pencolor), self._color(self._fillcolor))
  2377.         return args
  2378.  
  2379.     
  2380.     def pencolor(self, *args):
  2381.         ''' Return or set the pencolor.
  2382.  
  2383.         Arguments:
  2384.         Four input formats are allowed:
  2385.           - pencolor()
  2386.             Return the current pencolor as color specification string,
  2387.             possibly in hex-number format (see example).
  2388.             May be used as input to another color/pencolor/fillcolor call.
  2389.           - pencolor(colorstring)
  2390.             s is a Tk color specification string, such as "red" or "yellow"
  2391.           - pencolor((r, g, b))
  2392.             *a tuple* of r, g, and b, which represent, an RGB color,
  2393.             and each of r, g, and b are in the range 0..colormode,
  2394.             where colormode is either 1.0 or 255
  2395.           - pencolor(r, g, b)
  2396.             r, g, and b represent an RGB color, and each of r, g, and b
  2397.             are in the range 0..colormode
  2398.  
  2399.         If turtleshape is a polygon, the outline of that polygon is drawn
  2400.         with the newly set pencolor.
  2401.  
  2402.         Example (for a Turtle instance named turtle):
  2403.         >>> turtle.pencolor(\'brown\')
  2404.         >>> tup = (0.2, 0.8, 0.55)
  2405.         >>> turtle.pencolor(tup)
  2406.         >>> turtle.pencolor()
  2407.         \'#33cc8c\'
  2408.         '''
  2409.         if args:
  2410.             color = self._colorstr(args)
  2411.             if color == self._pencolor:
  2412.                 return None
  2413.             self.pen(pencolor = color)
  2414.         else:
  2415.             return self._color(self._pencolor)
  2416.         return color == self._pencolor
  2417.  
  2418.     
  2419.     def fillcolor(self, *args):
  2420.         ''' Return or set the fillcolor.
  2421.  
  2422.         Arguments:
  2423.         Four input formats are allowed:
  2424.           - fillcolor()
  2425.             Return the current fillcolor as color specification string,
  2426.             possibly in hex-number format (see example).
  2427.             May be used as input to another color/pencolor/fillcolor call.
  2428.           - fillcolor(colorstring)
  2429.             s is a Tk color specification string, such as "red" or "yellow"
  2430.           - fillcolor((r, g, b))
  2431.             *a tuple* of r, g, and b, which represent, an RGB color,
  2432.             and each of r, g, and b are in the range 0..colormode,
  2433.             where colormode is either 1.0 or 255
  2434.           - fillcolor(r, g, b)
  2435.             r, g, and b represent an RGB color, and each of r, g, and b
  2436.             are in the range 0..colormode
  2437.  
  2438.         If turtleshape is a polygon, the interior of that polygon is drawn
  2439.         with the newly set fillcolor.
  2440.  
  2441.         Example (for a Turtle instance named turtle):
  2442.         >>> turtle.fillcolor(\'violet\')
  2443.         >>> col = turtle.pencolor()
  2444.         >>> turtle.fillcolor(col)
  2445.         >>> turtle.fillcolor(0, .5, 0)
  2446.         '''
  2447.         if args:
  2448.             color = self._colorstr(args)
  2449.             if color == self._fillcolor:
  2450.                 return None
  2451.             self.pen(fillcolor = color)
  2452.         else:
  2453.             return self._color(self._fillcolor)
  2454.         return color == self._fillcolor
  2455.  
  2456.     
  2457.     def showturtle(self):
  2458.         '''Makes the turtle visible.
  2459.  
  2460.         Aliases: showturtle | st
  2461.  
  2462.         No argument.
  2463.  
  2464.         Example (for a Turtle instance named turtle):
  2465.         >>> turtle.hideturtle()
  2466.         >>> turtle.showturtle()
  2467.         '''
  2468.         self.pen(shown = True)
  2469.  
  2470.     
  2471.     def hideturtle(self):
  2472.         """Makes the turtle invisible.
  2473.  
  2474.         Aliases: hideturtle | ht
  2475.  
  2476.         No argument.
  2477.  
  2478.         It's a good idea to do this while you're in the
  2479.         middle of a complicated drawing, because hiding
  2480.         the turtle speeds up the drawing observably.
  2481.  
  2482.         Example (for a Turtle instance named turtle):
  2483.         >>> turtle.hideturtle()
  2484.         """
  2485.         self.pen(shown = False)
  2486.  
  2487.     
  2488.     def isvisible(self):
  2489.         """Return True if the Turtle is shown, False if it's hidden.
  2490.  
  2491.         No argument.
  2492.  
  2493.         Example (for a Turtle instance named turtle):
  2494.         >>> turtle.hideturtle()
  2495.         >>> print turtle.isvisible():
  2496.         False
  2497.         """
  2498.         return self._shown
  2499.  
  2500.     
  2501.     def pen(self, pen = None, **pendict):
  2502.         '''Return or set the pen\'s attributes.
  2503.  
  2504.         Arguments:
  2505.             pen -- a dictionary with some or all of the below listed keys.
  2506.             **pendict -- one or more keyword-arguments with the below
  2507.                          listed keys as keywords.
  2508.  
  2509.         Return or set the pen\'s attributes in a \'pen-dictionary\'
  2510.         with the following key/value pairs:
  2511.            "shown"      :   True/False
  2512.            "pendown"    :   True/False
  2513.            "pencolor"   :   color-string or color-tuple
  2514.            "fillcolor"  :   color-string or color-tuple
  2515.            "pensize"    :   positive number
  2516.            "speed"      :   number in range 0..10
  2517.            "resizemode" :   "auto" or "user" or "noresize"
  2518.            "stretchfactor": (positive number, positive number)
  2519.            "outline"    :   positive number
  2520.            "tilt"       :   number
  2521.  
  2522.         This dictionary can be used as argument for a subsequent
  2523.         pen()-call to restore the former pen-state. Moreover one
  2524.         or more of these attributes can be provided as keyword-arguments.
  2525.         This can be used to set several pen attributes in one statement.
  2526.  
  2527.  
  2528.         Examples (for a Turtle instance named turtle):
  2529.         >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
  2530.         >>> turtle.pen()
  2531.         {\'pensize\': 10, \'shown\': True, \'resizemode\': \'auto\', \'outline\': 1,
  2532.         \'pencolor\': \'red\', \'pendown\': True, \'fillcolor\': \'black\',
  2533.         \'stretchfactor\': (1,1), \'speed\': 3}
  2534.         >>> penstate=turtle.pen()
  2535.         >>> turtle.color("yellow","")
  2536.         >>> turtle.penup()
  2537.         >>> turtle.pen()
  2538.         {\'pensize\': 10, \'shown\': True, \'resizemode\': \'auto\', \'outline\': 1,
  2539.         \'pencolor\': \'yellow\', \'pendown\': False, \'fillcolor\': \'\',
  2540.         \'stretchfactor\': (1,1), \'speed\': 3}
  2541.         >>> p.pen(penstate, fillcolor="green")
  2542.         >>> p.pen()
  2543.         {\'pensize\': 10, \'shown\': True, \'resizemode\': \'auto\', \'outline\': 1,
  2544.         \'pencolor\': \'red\', \'pendown\': True, \'fillcolor\': \'green\',
  2545.         \'stretchfactor\': (1,1), \'speed\': 3}
  2546.         '''
  2547.         _pd = {
  2548.             'shown': self._shown,
  2549.             'pendown': self._drawing,
  2550.             'pencolor': self._pencolor,
  2551.             'fillcolor': self._fillcolor,
  2552.             'pensize': self._pensize,
  2553.             'speed': self._speed,
  2554.             'resizemode': self._resizemode,
  2555.             'stretchfactor': self._stretchfactor,
  2556.             'outline': self._outlinewidth,
  2557.             'tilt': self._tilt }
  2558.         if not pen or pendict:
  2559.             return _pd
  2560.         if isinstance(pen, dict):
  2561.             p = pen
  2562.         else:
  2563.             p = { }
  2564.         p.update(pendict)
  2565.         _p_buf = { }
  2566.         for key in p:
  2567.             _p_buf[key] = _pd[key]
  2568.         
  2569.         if self.undobuffer:
  2570.             self.undobuffer.push(('pen', _p_buf))
  2571.         
  2572.         newLine = False
  2573.         if 'pendown' in p:
  2574.             if self._drawing != p['pendown']:
  2575.                 newLine = True
  2576.             
  2577.         
  2578.         if 'pencolor' in p:
  2579.             if isinstance(p['pencolor'], tuple):
  2580.                 p['pencolor'] = self._colorstr((p['pencolor'],))
  2581.             
  2582.             if self._pencolor != p['pencolor']:
  2583.                 newLine = True
  2584.             
  2585.         
  2586.         if 'pensize' in p:
  2587.             if self._pensize != p['pensize']:
  2588.                 newLine = True
  2589.             
  2590.         
  2591.         if newLine:
  2592.             self._newLine()
  2593.         
  2594.         if 'pendown' in p:
  2595.             self._drawing = p['pendown']
  2596.         
  2597.         if 'pencolor' in p:
  2598.             self._pencolor = p['pencolor']
  2599.         
  2600.         if 'pensize' in p:
  2601.             self._pensize = p['pensize']
  2602.         
  2603.         if 'fillcolor' in p:
  2604.             if isinstance(p['fillcolor'], tuple):
  2605.                 p['fillcolor'] = self._colorstr((p['fillcolor'],))
  2606.             
  2607.             self._fillcolor = p['fillcolor']
  2608.         
  2609.         if 'speed' in p:
  2610.             self._speed = p['speed']
  2611.         
  2612.         if 'resizemode' in p:
  2613.             self._resizemode = p['resizemode']
  2614.         
  2615.         if 'stretchfactor' in p:
  2616.             sf = p['stretchfactor']
  2617.             if isinstance(sf, (int, float)):
  2618.                 sf = (sf, sf)
  2619.             
  2620.             self._stretchfactor = sf
  2621.         
  2622.         if 'outline' in p:
  2623.             self._outlinewidth = p['outline']
  2624.         
  2625.         if 'shown' in p:
  2626.             self._shown = p['shown']
  2627.         
  2628.         if 'tilt' in p:
  2629.             self._tilt = p['tilt']
  2630.         
  2631.         self._update()
  2632.  
  2633.     
  2634.     def _newLine(self, usePos = True):
  2635.         '''dummy method - to be overwritten by child class'''
  2636.         pass
  2637.  
  2638.     
  2639.     def _update(self, count = True, forced = False):
  2640.         '''dummy method - to be overwritten by child class'''
  2641.         pass
  2642.  
  2643.     
  2644.     def _color(self, args):
  2645.         '''dummy method - to be overwritten by child class'''
  2646.         pass
  2647.  
  2648.     
  2649.     def _colorstr(self, args):
  2650.         '''dummy method - to be overwritten by child class'''
  2651.         pass
  2652.  
  2653.     width = pensize
  2654.     up = penup
  2655.     pu = penup
  2656.     pd = pendown
  2657.     down = pendown
  2658.     st = showturtle
  2659.     ht = hideturtle
  2660.  
  2661.  
  2662. class _TurtleImage(object):
  2663.     '''Helper class: Datatype to store Turtle attributes
  2664.     '''
  2665.     
  2666.     def __init__(self, screen, shapeIndex):
  2667.         self.screen = screen
  2668.         self._type = None
  2669.         self._setshape(shapeIndex)
  2670.  
  2671.     
  2672.     def _setshape(self, shapeIndex):
  2673.         screen = self.screen
  2674.         self.shapeIndex = shapeIndex
  2675.         if 'polygon' == 'polygon':
  2676.             pass
  2677.         elif 'polygon' == screen._shapes[shapeIndex]._type:
  2678.             return None
  2679.         if 'image' == 'image':
  2680.             pass
  2681.         elif 'image' == screen._shapes[shapeIndex]._type:
  2682.             return None
  2683.         if self._type in ('image', 'polygon'):
  2684.             screen._delete(self._item)
  2685.         elif self._type == 'compound':
  2686.             for item in self._item:
  2687.                 screen._delete(item)
  2688.             
  2689.         
  2690.         self._type = screen._shapes[shapeIndex]._type
  2691.         if self._type == 'polygon':
  2692.             self._item = screen._createpoly()
  2693.         elif self._type == 'image':
  2694.             self._item = screen._createimage(screen._shapes['blank']._data)
  2695.         elif self._type == 'compound':
  2696.             self._item = [ screen._createpoly() for item in screen._shapes[shapeIndex]._data ]
  2697.         
  2698.  
  2699.  
  2700.  
  2701. class RawTurtle(TPen, TNavigator):
  2702.     '''Animation part of the RawTurtle.
  2703.     Puts RawTurtle upon a TurtleScreen and provides tools for
  2704.     its animation.
  2705.     '''
  2706.     screens = []
  2707.     
  2708.     def __init__(self, canvas = None, shape = _CFG['shape'], undobuffersize = _CFG['undobuffersize'], visible = _CFG['visible']):
  2709.         if isinstance(canvas, _Screen):
  2710.             self.screen = canvas
  2711.         elif isinstance(canvas, TurtleScreen):
  2712.             if canvas not in RawTurtle.screens:
  2713.                 RawTurtle.screens.append(canvas)
  2714.             
  2715.             self.screen = canvas
  2716.         elif isinstance(canvas, (ScrolledCanvas, Canvas)):
  2717.             for screen in RawTurtle.screens:
  2718.                 if screen.cv == canvas:
  2719.                     self.screen = screen
  2720.                     break
  2721.                     continue
  2722.             else:
  2723.                 self.screen = TurtleScreen(canvas)
  2724.         else:
  2725.             raise TurtleGraphicsError('bad cavas argument %s' % canvas)
  2726.         screen = isinstance(canvas, _Screen).screen
  2727.         TNavigator.__init__(self, screen.mode())
  2728.         TPen.__init__(self)
  2729.         screen._turtles.append(self)
  2730.         self.drawingLineItem = screen._createline()
  2731.         self.turtle = _TurtleImage(screen, shape)
  2732.         self._poly = None
  2733.         self._creatingPoly = False
  2734.         self._fillitem = None
  2735.         self._fillpath = None
  2736.         self._shown = visible
  2737.         self._hidden_from_screen = False
  2738.         self.currentLineItem = screen._createline()
  2739.         self.currentLine = [
  2740.             self._position]
  2741.         self.items = [
  2742.             self.currentLineItem]
  2743.         self.stampItems = []
  2744.         self._undobuffersize = undobuffersize
  2745.         self.undobuffer = Tbuffer(undobuffersize)
  2746.         self._update()
  2747.  
  2748.     
  2749.     def reset(self):
  2750.         """Delete the turtle's drawings and restore its default values.
  2751.  
  2752.         No argument.
  2753. ,
  2754.         Delete the turtle's drawings from the screen, re-center the turtle
  2755.         and set variables to the default values.
  2756.  
  2757.         Example (for a Turtle instance named turtle):
  2758.         >>> turtle.position()
  2759.         (0.00,-22.00)
  2760.         >>> turtle.heading()
  2761.         100.0
  2762.         >>> turtle.reset()
  2763.         >>> turtle.position()
  2764.         (0.00,0.00)
  2765.         >>> turtle.heading()
  2766.         0.0
  2767.         """
  2768.         TNavigator.reset(self)
  2769.         TPen._reset(self)
  2770.         self._clear()
  2771.         self._drawturtle()
  2772.         self._update()
  2773.  
  2774.     
  2775.     def setundobuffer(self, size):
  2776.         '''Set or disable undobuffer.
  2777.  
  2778.         Argument:
  2779.         size -- an integer or None
  2780.  
  2781.         If size is an integer an empty undobuffer of given size is installed.
  2782.         Size gives the maximum number of turtle-actions that can be undone
  2783.         by the undo() function.
  2784.         If size is None, no undobuffer is present.
  2785.  
  2786.         Example (for a Turtle instance named turtle):
  2787.         >>> turtle.setundobuffer(42)
  2788.         '''
  2789.         if size is None:
  2790.             self.undobuffer = None
  2791.         else:
  2792.             self.undobuffer = Tbuffer(size)
  2793.  
  2794.     
  2795.     def undobufferentries(self):
  2796.         '''Return count of entries in the undobuffer.
  2797.  
  2798.         No argument.
  2799.  
  2800.         Example (for a Turtle instance named turtle):
  2801.         >>> while undobufferentries():
  2802.                 undo()
  2803.         '''
  2804.         if self.undobuffer is None:
  2805.             return 0
  2806.         return self.undobuffer.nr_of_items()
  2807.  
  2808.     
  2809.     def _clear(self):
  2810.         """Delete all of pen's drawings"""
  2811.         self._fillitem = None
  2812.         self._fillpath = None
  2813.         for item in self.items:
  2814.             self.screen._delete(item)
  2815.         
  2816.         self.currentLineItem = self.screen._createline()
  2817.         self.currentLine = []
  2818.         if self._drawing:
  2819.             self.currentLine.append(self._position)
  2820.         
  2821.         self.items = [
  2822.             self.currentLineItem]
  2823.         self.clearstamps()
  2824.         self.setundobuffer(self._undobuffersize)
  2825.  
  2826.     
  2827.     def clear(self):
  2828.         """Delete the turtle's drawings from the screen. Do not move turtle.
  2829.  
  2830.         No arguments.
  2831.  
  2832.         Delete the turtle's drawings from the screen. Do not move turtle.
  2833.         State and position of the turtle as well as drawings of other
  2834.         turtles are not affected.
  2835.  
  2836.         Examples (for a Turtle instance named turtle):
  2837.         >>> turtle.clear()
  2838.         """
  2839.         self._clear()
  2840.         self._update()
  2841.  
  2842.     
  2843.     def _update_data(self):
  2844.         self.screen._incrementudc()
  2845.         if self.screen._updatecounter != 0:
  2846.             return None
  2847.         if len(self.currentLine) > 1:
  2848.             self.screen._drawline(self.currentLineItem, self.currentLine, self._pencolor, self._pensize)
  2849.         
  2850.  
  2851.     
  2852.     def _update(self):
  2853.         '''Perform a Turtle-data update.
  2854.         '''
  2855.         screen = self.screen
  2856.         if screen._tracing == 0:
  2857.             return None
  2858.         if screen._tracing == 1:
  2859.             self._update_data()
  2860.             self._drawturtle()
  2861.             screen._update()
  2862.             screen._delay(screen._delayvalue)
  2863.         else:
  2864.             self._update_data()
  2865.             if screen._updatecounter == 0:
  2866.                 for t in screen.turtles():
  2867.                     t._drawturtle()
  2868.                 
  2869.                 screen._update()
  2870.             
  2871.  
  2872.     
  2873.     def tracer(self, flag = None, delay = None):
  2874.         '''Turns turtle animation on/off and set delay for update drawings.
  2875.  
  2876.         Optional arguments:
  2877.         n -- nonnegative  integer
  2878.         delay -- nonnegative  integer
  2879.  
  2880.         If n is given, only each n-th regular screen update is really performed.
  2881.         (Can be used to accelerate the drawing of complex graphics.)
  2882.         Second arguments sets delay value (see RawTurtle.delay())
  2883.  
  2884.         Example (for a Turtle instance named turtle):
  2885.         >>> turtle.tracer(8, 25)
  2886.         >>> dist = 2
  2887.         >>> for i in range(200):
  2888.                 turtle.fd(dist)
  2889.                 turtle.rt(90)
  2890.                 dist += 2
  2891.         '''
  2892.         return self.screen.tracer(flag, delay)
  2893.  
  2894.     
  2895.     def _color(self, args):
  2896.         return self.screen._color(args)
  2897.  
  2898.     
  2899.     def _colorstr(self, args):
  2900.         return self.screen._colorstr(args)
  2901.  
  2902.     
  2903.     def _cc(self, args):
  2904.         '''Convert colortriples to hexstrings.
  2905.         '''
  2906.         if isinstance(args, str):
  2907.             return args
  2908.         
  2909.         try:
  2910.             (r, g, b) = args
  2911.         except:
  2912.             isinstance(args, str)
  2913.             raise TurtleGraphicsError('bad color arguments: %s' % str(args))
  2914.  
  2915.         if r <= r:
  2916.             pass
  2917.         elif r <= 255:
  2918.             if g <= g:
  2919.                 pass
  2920.             elif g <= 255:
  2921.                 if b <= b:
  2922.                     pass
  2923.                 elif not b <= 255:
  2924.                     raise TurtleGraphicsError('bad color sequence: %s' % str(args))
  2925.                 
  2926.         return '#%02x%02x%02x' % (r, g, b)
  2927.  
  2928.     
  2929.     def clone(self):
  2930.         '''Create and return a clone of the turtle.
  2931.  
  2932.         No argument.
  2933.  
  2934.         Create and return a clone of the turtle with same position, heading
  2935.         and turtle properties.
  2936.  
  2937.         Example (for a Turtle instance named mick):
  2938.         mick = Turtle()
  2939.         joe = mick.clone()
  2940.         '''
  2941.         screen = self.screen
  2942.         self._newLine(self._drawing)
  2943.         turtle = self.turtle
  2944.         self.screen = None
  2945.         self.turtle = None
  2946.         q = deepcopy(self)
  2947.         self.screen = screen
  2948.         self.turtle = turtle
  2949.         q.screen = screen
  2950.         q.turtle = _TurtleImage(screen, self.turtle.shapeIndex)
  2951.         screen._turtles.append(q)
  2952.         ttype = screen._shapes[self.turtle.shapeIndex]._type
  2953.         if ttype == 'polygon':
  2954.             q.turtle._item = screen._createpoly()
  2955.         elif ttype == 'image':
  2956.             q.turtle._item = screen._createimage(screen._shapes['blank']._data)
  2957.         elif ttype == 'compound':
  2958.             q.turtle._item = [ screen._createpoly() for item in screen._shapes[self.turtle.shapeIndex]._data ]
  2959.         
  2960.         q.currentLineItem = screen._createline()
  2961.         q._update()
  2962.         return q
  2963.  
  2964.     
  2965.     def shape(self, name = None):
  2966.         '''Set turtle shape to shape with given name / return current shapename.
  2967.  
  2968.         Optional argument:
  2969.         name -- a string, which is a valid shapename
  2970.  
  2971.         Set turtle shape to shape with given name or, if name is not given,
  2972.         return name of current shape.
  2973.         Shape with name must exist in the TurtleScreen\'s shape dictionary.
  2974.         Initially there are the following polygon shapes:
  2975.         \'arrow\', \'turtle\', \'circle\', \'square\', \'triangle\', \'classic\'.
  2976.         To learn about how to deal with shapes see Screen-method register_shape.
  2977.  
  2978.         Example (for a Turtle instance named turtle):
  2979.         >>> turtle.shape()
  2980.         \'arrow\'
  2981.         >>> turtle.shape("turtle")
  2982.         >>> turtle.shape()
  2983.         \'turtle\'
  2984.         '''
  2985.         if name is None:
  2986.             return self.turtle.shapeIndex
  2987.         if name not in self.screen.getshapes():
  2988.             raise TurtleGraphicsError('There is no shape named %s' % name)
  2989.         name not in self.screen.getshapes()
  2990.         self.turtle._setshape(name)
  2991.         self._update()
  2992.  
  2993.     
  2994.     def shapesize(self, stretch_wid = None, stretch_len = None, outline = None):
  2995.         '''Set/return turtle\'s stretchfactors/outline. Set resizemode to "user".
  2996.  
  2997.         Optinonal arguments:
  2998.            stretch_wid : positive number
  2999.            stretch_len : positive number
  3000.            outline  : positive number
  3001.  
  3002.         Return or set the pen\'s attributes x/y-stretchfactors and/or outline.
  3003.         Set resizemode to "user".
  3004.         If and only if resizemode is set to "user", the turtle will be displayed
  3005.         stretched according to its stretchfactors:
  3006.         stretch_wid is stretchfactor perpendicular to orientation
  3007.         stretch_len is stretchfactor in direction of turtles orientation.
  3008.         outline determines the width of the shapes\'s outline.
  3009.  
  3010.         Examples (for a Turtle instance named turtle):
  3011.         >>> turtle.resizemode("user")
  3012.         >>> turtle.shapesize(5, 5, 12)
  3013.         >>> turtle.shapesize(outline=8)
  3014.         '''
  3015.         if stretch_wid is None and stretch_len is None and outline == None:
  3016.             (stretch_wid, stretch_len) = self._stretchfactor
  3017.             return (stretch_wid, stretch_len, self._outlinewidth)
  3018.         if stretch_wid is not None:
  3019.             if stretch_len is None:
  3020.                 stretchfactor = (stretch_wid, stretch_wid)
  3021.             else:
  3022.                 stretchfactor = (stretch_wid, stretch_len)
  3023.         elif stretch_len is not None:
  3024.             stretchfactor = (self._stretchfactor[0], stretch_len)
  3025.         else:
  3026.             stretchfactor = self._stretchfactor
  3027.         if outline is None:
  3028.             outline = self._outlinewidth
  3029.         
  3030.         self.pen(resizemode = 'user', stretchfactor = stretchfactor, outline = outline)
  3031.  
  3032.     
  3033.     def settiltangle(self, angle):
  3034.         '''Rotate the turtleshape to point in the specified direction
  3035.  
  3036.         Optional argument:
  3037.         angle -- number
  3038.  
  3039.         Rotate the turtleshape to point in the direction specified by angle,
  3040.         regardless of its current tilt-angle. DO NOT change the turtle\'s
  3041.         heading (direction of movement).
  3042.  
  3043.  
  3044.         Examples (for a Turtle instance named turtle):
  3045.         >>> turtle.shape("circle")
  3046.         >>> turtle.shapesize(5,2)
  3047.         >>> turtle.settiltangle(45)
  3048.         >>> stamp()
  3049.         >>> turtle.fd(50)
  3050.         >>> turtle.settiltangle(-45)
  3051.         >>> stamp()
  3052.         >>> turtle.fd(50)
  3053.         '''
  3054.         tilt = -angle * self._degreesPerAU * self._angleOrient
  3055.         tilt = tilt * math.pi / 180 % 2 * math.pi
  3056.         self.pen(resizemode = 'user', tilt = tilt)
  3057.  
  3058.     
  3059.     def tiltangle(self):
  3060.         '''Return the current tilt-angle.
  3061.  
  3062.         No argument.
  3063.  
  3064.         Return the current tilt-angle, i. e. the angle between the
  3065.         orientation of the turtleshape and the heading of the turtle
  3066.         (its direction of movement).
  3067.  
  3068.         Examples (for a Turtle instance named turtle):
  3069.         >>> turtle.shape("circle")
  3070.         >>> turtle.shapesize(5,2)
  3071.         >>> turtle.tilt(45)
  3072.         >>> turtle.tiltangle()
  3073.         >>>
  3074.         '''
  3075.         tilt = -(self._tilt) * (180 / math.pi) * self._angleOrient
  3076.         return tilt / self._degreesPerAU % self._fullcircle
  3077.  
  3078.     
  3079.     def tilt(self, angle):
  3080.         '''Rotate the turtleshape by angle.
  3081.  
  3082.         Argument:
  3083.         angle - a number
  3084.  
  3085.         Rotate the turtleshape by angle from its current tilt-angle,
  3086.         but do NOT change the turtle\'s heading (direction of movement).
  3087.  
  3088.         Examples (for a Turtle instance named turtle):
  3089.         >>> turtle.shape("circle")
  3090.         >>> turtle.shapesize(5,2)
  3091.         >>> turtle.tilt(30)
  3092.         >>> turtle.fd(50)
  3093.         >>> turtle.tilt(30)
  3094.         >>> turtle.fd(50)
  3095.         '''
  3096.         self.settiltangle(angle + self.tiltangle())
  3097.  
  3098.     
  3099.     def _polytrafo(self, poly):
  3100.         '''Computes transformed polygon shapes from a shape
  3101.         according to current position and heading.
  3102.         '''
  3103.         screen = self.screen
  3104.         (p0, p1) = self._position
  3105.         (e0, e1) = self._orient
  3106.         e = Vec2D(e0, e1 * screen.yscale / screen.xscale)
  3107.         (e0, e1) = (1 / abs(e)) * e
  3108.         return [ (p0 + (e1 * x + e0 * y) / screen.xscale, p1 + (-e0 * x + e1 * y) / screen.yscale) for x, y in poly ]
  3109.  
  3110.     
  3111.     def _drawturtle(self):
  3112.         '''Manages the correct rendering of the turtle with respect to
  3113.         its shape, resizemode, stretch and tilt etc.'''
  3114.         screen = self.screen
  3115.         shape = screen._shapes[self.turtle.shapeIndex]
  3116.         ttype = shape._type
  3117.         titem = self.turtle._item
  3118.         None if self._shown and screen._updatecounter == 0 and screen._tracing > 0 else None
  3119.         if ttype == 'polygon':
  3120.             screen._drawpoly(titem, ((0, 0), (0, 0), (0, 0)), '', '')
  3121.         elif ttype == 'image':
  3122.             screen._drawimage(titem, self._position, screen._shapes['blank']._data)
  3123.         elif ttype == 'compound':
  3124.             for item in titem:
  3125.                 screen._drawpoly(item, ((0, 0), (0, 0), (0, 0)), '', '')
  3126.             
  3127.         
  3128.         self._hidden_from_screen = True
  3129.  
  3130.     
  3131.     def stamp(self):
  3132.         '''Stamp a copy of the turtleshape onto the canvas and return its id.
  3133.  
  3134.         No argument.
  3135.  
  3136.         Stamp a copy of the turtle shape onto the canvas at the current
  3137.         turtle position. Return a stamp_id for that stamp, which can be
  3138.         used to delete it by calling clearstamp(stamp_id).
  3139.  
  3140.         Example (for a Turtle instance named turtle):
  3141.         >>> turtle.color("blue")
  3142.         >>> turtle.stamp()
  3143.         13
  3144.         >>> turtle.fd(50)
  3145.         '''
  3146.         screen = self.screen
  3147.         shape = screen._shapes[self.turtle.shapeIndex]
  3148.         ttype = shape._type
  3149.         tshape = shape._data
  3150.         if ttype == 'polygon':
  3151.             stitem = screen._createpoly()
  3152.             if self._resizemode == 'noresize':
  3153.                 w = 1
  3154.                 shape = tshape
  3155.             elif self._resizemode == 'auto':
  3156.                 lx = ly = max(1, self._pensize / 5)
  3157.                 w = self._pensize
  3158.                 tiltangle = 0
  3159.             elif self._resizemode == 'user':
  3160.                 (lx, ly) = self._stretchfactor
  3161.                 w = self._outlinewidth
  3162.                 tiltangle = self._tilt
  3163.             
  3164.             shape = [ (lx * x, ly * y) for x, y in tshape ]
  3165.             t0 = math.sin(tiltangle)
  3166.             t1 = math.cos(tiltangle)
  3167.             shape = [ (t1 * x + t0 * y, -t0 * x + t1 * y) for x, y in shape ]
  3168.             shape = self._polytrafo(shape)
  3169.             fc = self._fillcolor
  3170.             oc = self._pencolor
  3171.             screen._drawpoly(stitem, shape, fill = fc, outline = oc, width = w, top = True)
  3172.         elif ttype == 'image':
  3173.             stitem = screen._createimage('')
  3174.             screen._drawimage(stitem, self._position, tshape)
  3175.         elif ttype == 'compound':
  3176.             stitem = []
  3177.             for element in tshape:
  3178.                 item = screen._createpoly()
  3179.                 stitem.append(item)
  3180.             
  3181.             stitem = tuple(stitem)
  3182.             (lx, ly) = self._stretchfactor
  3183.             w = self._outlinewidth
  3184.             for poly, fc, oc in zip(stitem, tshape):
  3185.                 poly = [ (lx * x, ly * y) for x, y in poly ]
  3186.                 poly = self._polytrafo(poly)
  3187.                 screen._drawpoly(item, poly, fill = self._cc(fc), outline = self._cc(oc), width = w, top = True)
  3188.             
  3189.         
  3190.         self.stampItems.append(stitem)
  3191.         self.undobuffer.push(('stamp', stitem))
  3192.         return stitem
  3193.  
  3194.     
  3195.     def _clearstamp(self, stampid):
  3196.         '''does the work for clearstamp() and clearstamps()
  3197.         '''
  3198.         if stampid in self.stampItems:
  3199.             if isinstance(stampid, tuple):
  3200.                 for subitem in stampid:
  3201.                     self.screen._delete(subitem)
  3202.                 
  3203.             else:
  3204.                 self.screen._delete(stampid)
  3205.             self.stampItems.remove(stampid)
  3206.         
  3207.         item = ('stamp', stampid)
  3208.         buf = self.undobuffer
  3209.         if item not in buf.buffer:
  3210.             return None
  3211.         index = buf.buffer.index(item)
  3212.         buf.buffer.remove(item)
  3213.         if index <= buf.ptr:
  3214.             buf.ptr = (buf.ptr - 1) % buf.bufsize
  3215.         
  3216.         buf.buffer.insert((buf.ptr + 1) % buf.bufsize, [
  3217.             None])
  3218.  
  3219.     
  3220.     def clearstamp(self, stampid):
  3221.         '''Delete stamp with given stampid
  3222.  
  3223.         Argument:
  3224.         stampid - an integer, must be return value of previous stamp() call.
  3225.  
  3226.         Example (for a Turtle instance named turtle):
  3227.         >>> turtle.color("blue")
  3228.         >>> astamp = turtle.stamp()
  3229.         >>> turtle.fd(50)
  3230.         >>> turtle.clearstamp(astamp)
  3231.         '''
  3232.         self._clearstamp(stampid)
  3233.         self._update()
  3234.  
  3235.     
  3236.     def clearstamps(self, n = None):
  3237.         """Delete all or first/last n of turtle's stamps.
  3238.  
  3239.         Optional argument:
  3240.         n -- an integer
  3241.  
  3242.         If n is None, delete all of pen's stamps,
  3243.         else if n > 0 delete first n stamps
  3244.         else if n < 0 delete last n stamps.
  3245.  
  3246.         Example (for a Turtle instance named turtle):
  3247.         >>> for i in range(8):
  3248.                 turtle.stamp(); turtle.fd(30)
  3249.         ...
  3250.         >>> turtle.clearstamps(2)
  3251.         >>> turtle.clearstamps(-2)
  3252.         >>> turtle.clearstamps()
  3253.         """
  3254.         if n is None:
  3255.             toDelete = self.stampItems[:]
  3256.         elif n >= 0:
  3257.             toDelete = self.stampItems[:n]
  3258.         else:
  3259.             toDelete = self.stampItems[n:]
  3260.         for item in toDelete:
  3261.             self._clearstamp(item)
  3262.         
  3263.         self._update()
  3264.  
  3265.     
  3266.     def _goto(self, end):
  3267.         '''Move the pen to the point end, thereby drawing a line
  3268.         if pen is down. All other methodes for turtle movement depend
  3269.         on this one.
  3270.         '''
  3271.         go_modes = (self._drawing, self._pencolor, self._pensize, isinstance(self._fillpath, list))
  3272.         screen = self.screen
  3273.         undo_entry = ('go', self._position, end, go_modes, (self.currentLineItem, self.currentLine[:], screen._pointlist(self.currentLineItem), self.items[:]))
  3274.         if self.undobuffer:
  3275.             self.undobuffer.push(undo_entry)
  3276.         
  3277.         start = self._position
  3278.         if self._speed and screen._tracing == 1:
  3279.             diff = end - start
  3280.             diffsq = (diff[0] * screen.xscale) ** 2 + (diff[1] * screen.yscale) ** 2
  3281.             nhops = 1 + int(diffsq ** 0.5 / 3 * 1.1 ** self._speed * self._speed)
  3282.             delta = diff * (1 / nhops)
  3283.             for n in range(1, nhops):
  3284.                 if n == 1:
  3285.                     top = True
  3286.                 else:
  3287.                     top = False
  3288.                 self._position = start + delta * n
  3289.                 if self._drawing:
  3290.                     screen._drawline(self.drawingLineItem, (start, self._position), self._pencolor, self._pensize, top)
  3291.                 
  3292.                 self._update()
  3293.             
  3294.             if self._drawing:
  3295.                 screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)), fill = '', width = self._pensize)
  3296.             
  3297.         
  3298.         if self._drawing:
  3299.             self.currentLine.append(end)
  3300.         
  3301.         if isinstance(self._fillpath, list):
  3302.             self._fillpath.append(end)
  3303.         
  3304.         self._position = end
  3305.         if self._creatingPoly:
  3306.             self._poly.append(end)
  3307.         
  3308.         if len(self.currentLine) > 42:
  3309.             self._newLine()
  3310.         
  3311.         self._update()
  3312.  
  3313.     
  3314.     def _undogoto(self, entry):
  3315.         '''Reverse a _goto. Used for undo()
  3316.         '''
  3317.         (old, new, go_modes, coodata) = entry
  3318.         (drawing, pc, ps, filling) = go_modes
  3319.         (cLI, cL, pl, items) = coodata
  3320.         screen = self.screen
  3321.         if abs(self._position - new) > 0.5:
  3322.             print 'undogoto: HALLO-DA-STIMMT-WAS-NICHT!'
  3323.         
  3324.         self.currentLineItem = cLI
  3325.         self.currentLine = cL
  3326.         if pl == [
  3327.             (0, 0),
  3328.             (0, 0)]:
  3329.             usepc = ''
  3330.         else:
  3331.             usepc = pc
  3332.         screen._drawline(cLI, pl, fill = usepc, width = ps)
  3333.         todelete = _[1]
  3334.         for i in todelete:
  3335.             screen._delete(i)
  3336.             self.items.remove(i)
  3337.         
  3338.         start = old
  3339.         if self._speed and screen._tracing == 1:
  3340.             diff = old - new
  3341.             diffsq = (diff[0] * screen.xscale) ** 2 + (diff[1] * screen.yscale) ** 2
  3342.             nhops = 1 + int(diffsq ** 0.5 / 3 * 1.1 ** self._speed * self._speed)
  3343.             delta = diff * (1 / nhops)
  3344.             for n in range(1, nhops):
  3345.                 self._position = new + delta * n
  3346.                 if drawing:
  3347.                     screen._drawline(self.drawingLineItem, (start, self._position), pc, ps, top)
  3348.                 
  3349.                 self._update()
  3350.             
  3351.             if drawing:
  3352.                 screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)), fill = '', width = ps)
  3353.             
  3354.         
  3355.         self._position = old
  3356.         if self._creatingPoly:
  3357.             if len(self._poly) > 0:
  3358.                 self._poly.pop()
  3359.             
  3360.             if self._poly == []:
  3361.                 self._creatingPoly = False
  3362.                 self._poly = None
  3363.             
  3364.         
  3365.         if filling:
  3366.             if self._fillpath == []:
  3367.                 self._fillpath = None
  3368.                 print 'Unwahrscheinlich in _undogoto!'
  3369.             elif self._fillpath is not None:
  3370.                 self._fillpath.pop()
  3371.             
  3372.         
  3373.         self._update()
  3374.  
  3375.     
  3376.     def _rotate(self, angle):
  3377.         '''Turns pen clockwise by angle.
  3378.         '''
  3379.         if self.undobuffer:
  3380.             self.undobuffer.push(('rot', angle, self._degreesPerAU))
  3381.         
  3382.         angle *= self._degreesPerAU
  3383.         neworient = self._orient.rotate(angle)
  3384.         tracing = self.screen._tracing
  3385.         if tracing == 1 and self._speed > 0:
  3386.             anglevel = 3 * self._speed
  3387.             steps = 1 + int(abs(angle) / anglevel)
  3388.             delta = 1 * angle / steps
  3389.             for _ in range(steps):
  3390.                 self._orient = self._orient.rotate(delta)
  3391.                 self._update()
  3392.             
  3393.         
  3394.         self._orient = neworient
  3395.         self._update()
  3396.  
  3397.     
  3398.     def _newLine(self, usePos = True):
  3399.         '''Closes current line item and starts a new one.
  3400.            Remark: if current line became too long, animation
  3401.            performance (via _drawline) slowed down considerably.
  3402.         '''
  3403.         if len(self.currentLine) > 1:
  3404.             self.screen._drawline(self.currentLineItem, self.currentLine, self._pencolor, self._pensize)
  3405.             self.currentLineItem = self.screen._createline()
  3406.             self.items.append(self.currentLineItem)
  3407.         else:
  3408.             self.screen._drawline(self.currentLineItem, top = True)
  3409.         self.currentLine = []
  3410.         if usePos:
  3411.             self.currentLine = [
  3412.                 self._position]
  3413.         
  3414.  
  3415.     
  3416.     def fill(self, flag = None):
  3417.         '''Call fill(True) before drawing a shape to fill, fill(False) when done.
  3418.  
  3419.         Optional argument:
  3420.         flag -- True/False (or 1/0 respectively)
  3421.  
  3422.         Call fill(True) before drawing the shape you want to fill,
  3423.         and  fill(False) when done.
  3424.         When used without argument: return fillstate (True if filling,
  3425.         False else)
  3426.  
  3427.         Example (for a Turtle instance named turtle):
  3428.         >>> turtle.fill(True)
  3429.         >>> turtle.forward(100)
  3430.         >>> turtle.left(90)
  3431.         >>> turtle.forward(100)
  3432.         >>> turtle.left(90)
  3433.         >>> turtle.forward(100)
  3434.         >>> turtle.left(90)
  3435.         >>> turtle.forward(100)
  3436.         >>> turtle.fill(False)
  3437.         '''
  3438.         filling = isinstance(self._fillpath, list)
  3439.         if flag is None:
  3440.             return filling
  3441.         screen = self.screen
  3442.         if flag:
  3443.             self._fillitem = self.screen._createpoly()
  3444.             self.items.append(self._fillitem)
  3445.             self._fillpath = [
  3446.                 self._position]
  3447.             entry2 = ('beginfill', self._fillitem)
  3448.             self._newLine()
  3449.         else:
  3450.             self._fillitem = None
  3451.             self._fillpath = None
  3452.         if self.undobuffer:
  3453.             if entry1 == ():
  3454.                 if entry2 != ():
  3455.                     self.undobuffer.push(entry2)
  3456.                 
  3457.             elif entry2 == ():
  3458.                 self.undobuffer.push(entry1)
  3459.             else:
  3460.                 self.undobuffer.push([
  3461.                     'seq',
  3462.                     entry1,
  3463.                     entry2])
  3464.         
  3465.         self._update()
  3466.  
  3467.     
  3468.     def begin_fill(self):
  3469.         '''Called just before drawing a shape to be filled.
  3470.  
  3471.         No argument.
  3472.  
  3473.         Example (for a Turtle instance named turtle):
  3474.         >>> turtle.begin_fill()
  3475.         >>> turtle.forward(100)
  3476.         >>> turtle.left(90)
  3477.         >>> turtle.forward(100)
  3478.         >>> turtle.left(90)
  3479.         >>> turtle.forward(100)
  3480.         >>> turtle.left(90)
  3481.         >>> turtle.forward(100)
  3482.         >>> turtle.end_fill()
  3483.         '''
  3484.         self.fill(True)
  3485.  
  3486.     
  3487.     def end_fill(self):
  3488.         '''Fill the shape drawn after the call begin_fill().
  3489.  
  3490.         No argument.
  3491.  
  3492.         Example (for a Turtle instance named turtle):
  3493.         >>> turtle.begin_fill()
  3494.         >>> turtle.forward(100)
  3495.         >>> turtle.left(90)
  3496.         >>> turtle.forward(100)
  3497.         >>> turtle.left(90)
  3498.         >>> turtle.forward(100)
  3499.         >>> turtle.left(90)
  3500.         >>> turtle.forward(100)
  3501.         >>> turtle.end_fill()
  3502.         '''
  3503.         self.fill(False)
  3504.  
  3505.     
  3506.     def dot(self, size = None, *color):
  3507.         '''Draw a dot with diameter size, using color.
  3508.  
  3509.         Optional argumentS:
  3510.         size -- an integer >= 1 (if given)
  3511.         color -- a colorstring or a numeric color tuple
  3512.  
  3513.         Draw a circular dot with diameter size, using color.
  3514.         If size is not given, the maximum of pensize+4 and 2*pensize is used.
  3515.  
  3516.         Example (for a Turtle instance named turtle):
  3517.         >>> turtle.dot()
  3518.         >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
  3519.         '''
  3520.         if not color:
  3521.             if isinstance(size, (str, tuple)):
  3522.                 color = self._colorstr(size)
  3523.                 size = self._pensize + max(self._pensize, 4)
  3524.             else:
  3525.                 color = self._pencolor
  3526.                 if not size:
  3527.                     size = self._pensize + max(self._pensize, 4)
  3528.                 
  3529.         elif size is None:
  3530.             size = self._pensize + max(self._pensize, 4)
  3531.         
  3532.         color = self._colorstr(color)
  3533.         if hasattr(self.screen, '_dot'):
  3534.             item = self.screen._dot(self._position, size, color)
  3535.             self.items.append(item)
  3536.             if self.undobuffer:
  3537.                 self.undobuffer.push(('dot', item))
  3538.             
  3539.         else:
  3540.             pen = self.pen()
  3541.             if self.undobuffer:
  3542.                 self.undobuffer.push([
  3543.                     'seq'])
  3544.                 self.undobuffer.cumulate = True
  3545.             
  3546.             
  3547.             try:
  3548.                 if self.resizemode() == 'auto':
  3549.                     self.ht()
  3550.                 
  3551.                 self.pendown()
  3552.                 self.pensize(size)
  3553.                 self.pencolor(color)
  3554.                 self.forward(0)
  3555.             finally:
  3556.                 self.pen(pen)
  3557.  
  3558.             if self.undobuffer:
  3559.                 self.undobuffer.cumulate = False
  3560.             
  3561.  
  3562.     
  3563.     def _write(self, txt, align, font):
  3564.         '''Performs the writing for write()
  3565.         '''
  3566.         (item, end) = self.screen._write(self._position, txt, align, font, self._pencolor)
  3567.         self.items.append(item)
  3568.         if self.undobuffer:
  3569.             self.undobuffer.push(('wri', item))
  3570.         
  3571.         return end
  3572.  
  3573.     
  3574.     def write(self, arg, move = False, align = 'left', font = ('Arial', 8, 'normal')):
  3575.         '''Write text at the current turtle position.
  3576.  
  3577.         Arguments:
  3578.         arg -- info, which is to be written to the TurtleScreen
  3579.         move (optional) -- True/False
  3580.         align (optional) -- one of the strings "left", "center" or right"
  3581.         font (optional) -- a triple (fontname, fontsize, fonttype)
  3582.  
  3583.         Write text - the string representation of arg - at the current
  3584.         turtle position according to align ("left", "center" or right")
  3585.         and with the given font.
  3586.         If move is True, the pen is moved to the bottom-right corner
  3587.         of the text. By default, move is False.
  3588.  
  3589.         Example (for a Turtle instance named turtle):
  3590.         >>> turtle.write(\'Home = \', True, align="center")
  3591.         >>> turtle.write((0,0), True)
  3592.         '''
  3593.         if self.undobuffer:
  3594.             self.undobuffer.push([
  3595.                 'seq'])
  3596.             self.undobuffer.cumulate = True
  3597.         
  3598.         end = self._write(str(arg), align.lower(), font)
  3599.         if move:
  3600.             (x, y) = self.pos()
  3601.             self.setpos(end, y)
  3602.         
  3603.         if self.undobuffer:
  3604.             self.undobuffer.cumulate = False
  3605.         
  3606.  
  3607.     
  3608.     def begin_poly(self):
  3609.         '''Start recording the vertices of a polygon.
  3610.  
  3611.         No argument.
  3612.  
  3613.         Start recording the vertices of a polygon. Current turtle position
  3614.         is first point of polygon.
  3615.  
  3616.         Example (for a Turtle instance named turtle):
  3617.         >>> turtle.begin_poly()
  3618.         '''
  3619.         self._poly = [
  3620.             self._position]
  3621.         self._creatingPoly = True
  3622.  
  3623.     
  3624.     def end_poly(self):
  3625.         '''Stop recording the vertices of a polygon.
  3626.  
  3627.         No argument.
  3628.  
  3629.         Stop recording the vertices of a polygon. Current turtle position is
  3630.         last point of polygon. This will be connected with the first point.
  3631.  
  3632.         Example (for a Turtle instance named turtle):
  3633.         >>> turtle.end_poly()
  3634.         '''
  3635.         self._creatingPoly = False
  3636.  
  3637.     
  3638.     def get_poly(self):
  3639.         '''Return the lastly recorded polygon.
  3640.  
  3641.         No argument.
  3642.  
  3643.         Example (for a Turtle instance named turtle):
  3644.         >>> p = turtle.get_poly()
  3645.         >>> turtle.register_shape("myFavouriteShape", p)
  3646.         '''
  3647.         if self._poly is not None:
  3648.             return tuple(self._poly)
  3649.  
  3650.     
  3651.     def getscreen(self):
  3652.         '''Return the TurtleScreen object, the turtle is drawing  on.
  3653.  
  3654.         No argument.
  3655.  
  3656.         Return the TurtleScreen object, the turtle is drawing  on.
  3657.         So TurtleScreen-methods can be called for that object.
  3658.  
  3659.         Example (for a Turtle instance named turtle):
  3660.         >>> ts = turtle.getscreen()
  3661.         >>> ts
  3662.         <turtle.TurtleScreen object at 0x0106B770>
  3663.         >>> ts.bgcolor("pink")
  3664.         '''
  3665.         return self.screen
  3666.  
  3667.     
  3668.     def getturtle(self):
  3669.         """Return the Turtleobject itself.
  3670.  
  3671.         No argument.
  3672.  
  3673.         Only reasonable use: as a function to return the 'anonymous turtle':
  3674.  
  3675.         Example:
  3676.         >>> pet = getturtle()
  3677.         >>> pet.fd(50)
  3678.         >>> pet
  3679.         <turtle.Turtle object at 0x0187D810>
  3680.         >>> turtles()
  3681.         [<turtle.Turtle object at 0x0187D810>]
  3682.         """
  3683.         return self
  3684.  
  3685.     getpen = getturtle
  3686.     
  3687.     def window_width(self):
  3688.         ''' Returns the width of the turtle window.
  3689.  
  3690.         No argument.
  3691.  
  3692.         Example (for a TurtleScreen instance named screen):
  3693.         >>> screen.window_width()
  3694.         640
  3695.         '''
  3696.         return self.screen._window_size()[0]
  3697.  
  3698.     
  3699.     def window_height(self):
  3700.         ''' Return the height of the turtle window.
  3701.  
  3702.         No argument.
  3703.  
  3704.         Example (for a TurtleScreen instance named screen):
  3705.         >>> screen.window_height()
  3706.         480
  3707.         '''
  3708.         return self.screen._window_size()[1]
  3709.  
  3710.     
  3711.     def _delay(self, delay = None):
  3712.         '''Set delay value which determines speed of turtle animation.
  3713.         '''
  3714.         return self.screen.delay(delay)
  3715.  
  3716.     
  3717.     def onclick(self, fun, btn = 1, add = None):
  3718.         '''Bind fun to mouse-click event on this turtle on canvas.
  3719.  
  3720.         Arguments:
  3721.         fun --  a function with two arguments, to which will be assigned
  3722.                 the coordinates of the clicked point on the canvas.
  3723.         num --  number of the mouse-button defaults to 1 (left mouse button).
  3724.         add --  True or False. If True, new binding will be added, otherwise
  3725.                 it will replace a former binding.
  3726.  
  3727.         Example for the anonymous turtle, i. e. the procedural way:
  3728.  
  3729.         >>> def turn(x, y):
  3730.                 left(360)
  3731.  
  3732.         >>> onclick(turn) # Now clicking into the turtle will turn it.
  3733.         >>> onclick(None)  # event-binding will be removed
  3734.         '''
  3735.         self.screen._onclick(self.turtle._item, fun, btn, add)
  3736.         self._update()
  3737.  
  3738.     
  3739.     def onrelease(self, fun, btn = 1, add = None):
  3740.         '''Bind fun to mouse-button-release event on this turtle on canvas.
  3741.  
  3742.         Arguments:
  3743.         fun -- a function with two arguments, to which will be assigned
  3744.                 the coordinates of the clicked point on the canvas.
  3745.         num --  number of the mouse-button defaults to 1 (left mouse button).
  3746.  
  3747.         Example (for a MyTurtle instance named joe):
  3748.         >>> class MyTurtle(Turtle):
  3749.                 def glow(self,x,y):
  3750.                         self.fillcolor("red")
  3751.                 def unglow(self,x,y):
  3752.                         self.fillcolor("")
  3753.  
  3754.         >>> joe = MyTurtle()
  3755.         >>> joe.onclick(joe.glow)
  3756.         >>> joe.onrelease(joe.unglow)
  3757.         ### clicking on joe turns fillcolor red,
  3758.         ### unclicking turns it to transparent.
  3759.         '''
  3760.         self.screen._onrelease(self.turtle._item, fun, btn, add)
  3761.         self._update()
  3762.  
  3763.     
  3764.     def ondrag(self, fun, btn = 1, add = None):
  3765.         '''Bind fun to mouse-move event on this turtle on canvas.
  3766.  
  3767.         Arguments:
  3768.         fun -- a function with two arguments, to which will be assigned
  3769.                the coordinates of the clicked point on the canvas.
  3770.         num -- number of the mouse-button defaults to 1 (left mouse button).
  3771.  
  3772.         Every sequence of mouse-move-events on a turtle is preceded by a
  3773.         mouse-click event on that turtle.
  3774.  
  3775.         Example (for a Turtle instance named turtle):
  3776.         >>> turtle.ondrag(turtle.goto)
  3777.  
  3778.         ### Subsequently clicking and dragging a Turtle will
  3779.         ### move it across the screen thereby producing handdrawings
  3780.         ### (if pen is down).
  3781.         '''
  3782.         self.screen._ondrag(self.turtle._item, fun, btn, add)
  3783.  
  3784.     
  3785.     def _undo(self, action, data):
  3786.         '''Does the main part of the work for undo()
  3787.         '''
  3788.         if self.undobuffer is None:
  3789.             return None
  3790.         if action == 'rot':
  3791.             (angle, degPAU) = data
  3792.             self._rotate(-angle * degPAU / self._degreesPerAU)
  3793.             dummy = self.undobuffer.pop()
  3794.         elif action == 'stamp':
  3795.             stitem = data[0]
  3796.             self.clearstamp(stitem)
  3797.         elif action == 'go':
  3798.             self._undogoto(data)
  3799.         elif action in ('wri', 'dot'):
  3800.             item = data[0]
  3801.             self.screen._delete(item)
  3802.             self.items.remove(item)
  3803.         elif action == 'dofill':
  3804.             item = data[0]
  3805.             self.screen._drawpoly(item, ((0, 0), (0, 0), (0, 0)), fill = '', outline = '')
  3806.         elif action == 'beginfill':
  3807.             item = data[0]
  3808.             self._fillitem = None
  3809.             self._fillpath = None
  3810.             self.screen._delete(item)
  3811.             self.items.remove(item)
  3812.         elif action == 'pen':
  3813.             TPen.pen(self, data[0])
  3814.             self.undobuffer.pop()
  3815.         
  3816.  
  3817.     
  3818.     def undo(self):
  3819.         '''undo (repeatedly) the last turtle action.
  3820.  
  3821.         No argument.
  3822.  
  3823.         undo (repeatedly) the last turtle action.
  3824.         Number of available undo actions is determined by the size of
  3825.         the undobuffer.
  3826.  
  3827.         Example (for a Turtle instance named turtle):
  3828.         >>> for i in range(4):
  3829.                 turtle.fd(50); turtle.lt(80)
  3830.  
  3831.         >>> for i in range(8):
  3832.                 turtle.undo()
  3833.         '''
  3834.         if self.undobuffer is None:
  3835.             return None
  3836.         item = self.undobuffer.pop()
  3837.         action = item[0]
  3838.         data = item[1:]
  3839.  
  3840.     turtlesize = shapesize
  3841.  
  3842. RawPen = RawTurtle
  3843.  
  3844. def Screen():
  3845.     '''Return the singleton screen object.
  3846.     If none exists at the moment, create a new one and return it,
  3847.     else return the existing one.'''
  3848.     if Turtle._screen is None:
  3849.         Turtle._screen = _Screen()
  3850.     
  3851.     return Turtle._screen
  3852.  
  3853.  
  3854. class _Screen(TurtleScreen):
  3855.     _root = None
  3856.     _canvas = None
  3857.     _title = _CFG['title']
  3858.     
  3859.     def __init__(self):
  3860.         if _Screen._root is None:
  3861.             _Screen._root = self._root = _Root()
  3862.             self._root.title(_Screen._title)
  3863.             self._root.ondestroy(self._destroy)
  3864.         
  3865.         if _Screen._canvas is None:
  3866.             width = _CFG['width']
  3867.             height = _CFG['height']
  3868.             canvwidth = _CFG['canvwidth']
  3869.             canvheight = _CFG['canvheight']
  3870.             leftright = _CFG['leftright']
  3871.             topbottom = _CFG['topbottom']
  3872.             self._root.setupcanvas(width, height, canvwidth, canvheight)
  3873.             _Screen._canvas = self._root._getcanvas()
  3874.             TurtleScreen.__init__(self, _Screen._canvas)
  3875.             self.setup(width, height, leftright, topbottom)
  3876.         
  3877.  
  3878.     
  3879.     def setup(self, width = _CFG['width'], height = _CFG['height'], startx = _CFG['leftright'], starty = _CFG['topbottom']):
  3880.         ''' Set the size and position of the main window.
  3881.  
  3882.         Arguments:
  3883.         width: as integer a size in pixels, as float a fraction of the screen.
  3884.           Default is 50% of screen.
  3885.         height: as integer the height in pixels, as float a fraction of the
  3886.           screen. Default is 75% of screen.
  3887.         startx: if positive, starting position in pixels from the left
  3888.           edge of the screen, if negative from the right edge
  3889.           Default, startx=None is to center window horizontally.
  3890.         starty: if positive, starting position in pixels from the top
  3891.           edge of the screen, if negative from the bottom edge
  3892.           Default, starty=None is to center window vertically.
  3893.  
  3894.         Examples (for a Screen instance named screen):
  3895.         >>> screen.setup (width=200, height=200, startx=0, starty=0)
  3896.  
  3897.         sets window to 200x200 pixels, in upper left of screen
  3898.  
  3899.         >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
  3900.  
  3901.         sets window to 75% of screen by 50% of screen and centers
  3902.         '''
  3903.         if not hasattr(self._root, 'set_geometry'):
  3904.             return None
  3905.         sw = self._root.win_width()
  3906.         sh = self._root.win_height()
  3907.         if isinstance(width, float):
  3908.             if width <= width:
  3909.                 pass
  3910.             elif width <= 1:
  3911.                 width = sw * width
  3912.             
  3913.         if startx is None:
  3914.             startx = (sw - width) / 2
  3915.         
  3916.         if isinstance(height, float):
  3917.             if height <= height:
  3918.                 pass
  3919.             elif height <= 1:
  3920.                 height = sh * height
  3921.             
  3922.         if starty is None:
  3923.             starty = (sh - height) / 2
  3924.         
  3925.         self._root.set_geometry(width, height, startx, starty)
  3926.         self.update()
  3927.  
  3928.     
  3929.     def title(self, titlestring):
  3930.         '''Set title of turtle-window
  3931.  
  3932.         Argument:
  3933.         titlestring -- a string, to appear in the titlebar of the
  3934.                        turtle graphics window.
  3935.  
  3936.         This is a method of Screen-class. Not available for TurtleScreen-
  3937.         objects.
  3938.  
  3939.         Example (for a Screen instance named screen):
  3940.         >>> screen.title("Welcome to the turtle-zoo!")
  3941.         '''
  3942.         if _Screen._root is not None:
  3943.             _Screen._root.title(titlestring)
  3944.         
  3945.         _Screen._title = titlestring
  3946.  
  3947.     
  3948.     def _destroy(self):
  3949.         root = self._root
  3950.         if root is _Screen._root:
  3951.             Turtle._pen = None
  3952.             Turtle._screen = None
  3953.             _Screen._root = None
  3954.             _Screen._canvas = None
  3955.         
  3956.         TurtleScreen._RUNNING = True
  3957.         root.destroy()
  3958.  
  3959.     
  3960.     def bye(self):
  3961.         '''Shut the turtlegraphics window.
  3962.  
  3963.         Example (for a TurtleScreen instance named screen):
  3964.         >>> screen.bye()
  3965.         '''
  3966.         self._destroy()
  3967.  
  3968.     
  3969.     def exitonclick(self):
  3970.         '''Go into mainloop until the mouse is clicked.
  3971.  
  3972.         No arguments.
  3973.  
  3974.         Bind bye() method to mouseclick on TurtleScreen.
  3975.         If "using_IDLE" - value in configuration dictionary is False
  3976.         (default value), enter mainloop.
  3977.         If IDLE with -n switch (no subprocess) is used, this value should be
  3978.         set to True in turtle.cfg. In this case IDLE\'s mainloop
  3979.         is active also for the client script.
  3980.  
  3981.         This is a method of the Screen-class and not available for
  3982.         TurtleScreen instances.
  3983.  
  3984.         Example (for a Screen instance named screen):
  3985.         >>> screen.exitonclick()
  3986.  
  3987.         '''
  3988.         
  3989.         def exitGracefully(x, y):
  3990.             '''Screen.bye() with two dummy-parameters'''
  3991.             self.bye()
  3992.  
  3993.         self.onclick(exitGracefully)
  3994.         if _CFG['using_IDLE']:
  3995.             return None
  3996.         
  3997.         try:
  3998.             mainloop()
  3999.         except AttributeError:
  4000.             _CFG['using_IDLE']
  4001.             _CFG['using_IDLE']
  4002.             (None,)
  4003.             exit(0)
  4004.         except:
  4005.             _CFG['using_IDLE']
  4006.  
  4007.  
  4008.  
  4009.  
  4010. class Turtle(RawTurtle):
  4011.     '''RawTurtle auto-crating (scrolled) canvas.
  4012.  
  4013.     When a Turtle object is created or a function derived from some
  4014.     Turtle method is called a TurtleScreen object is automatically created.
  4015.     '''
  4016.     _pen = None
  4017.     _screen = None
  4018.     
  4019.     def __init__(self, shape = _CFG['shape'], undobuffersize = _CFG['undobuffersize'], visible = _CFG['visible']):
  4020.         if Turtle._screen is None:
  4021.             Turtle._screen = Screen()
  4022.         
  4023.         RawTurtle.__init__(self, Turtle._screen, shape = shape, undobuffersize = undobuffersize, visible = visible)
  4024.  
  4025.  
  4026. Pen = Turtle
  4027.  
  4028. def _getpen():
  4029.     """Create the 'anonymous' turtle if not already present."""
  4030.     if Turtle._pen is None:
  4031.         Turtle._pen = Turtle()
  4032.     
  4033.     return Turtle._pen
  4034.  
  4035.  
  4036. def _getscreen():
  4037.     '''Create a TurtleScreen if not already present.'''
  4038.     if Turtle._screen is None:
  4039.         Turtle._screen = Screen()
  4040.     
  4041.     return Turtle._screen
  4042.  
  4043.  
  4044. def write_docstringdict(filename = 'turtle_docstringdict'):
  4045.     '''Create and write docstring-dictionary to file.
  4046.  
  4047.     Optional argument:
  4048.     filename -- a string, used as filename
  4049.                 default value is turtle_docstringdict
  4050.  
  4051.     Has to be called explicitely, (not used by the turtle-graphics classes)
  4052.     The docstring dictionary will be written to the Python script <filname>.py
  4053.     It is intended to serve as a template for translation of the docstrings
  4054.     into different languages.
  4055.     '''
  4056.     docsdict = { }
  4057.     for methodname in _tg_screen_functions:
  4058.         key = '_Screen.' + methodname
  4059.         docsdict[key] = eval(key).__doc__
  4060.     
  4061.     for methodname in _tg_turtle_functions:
  4062.         key = 'Turtle.' + methodname
  4063.         docsdict[key] = eval(key).__doc__
  4064.     
  4065.     f = open('%s.py' % filename, 'w')
  4066.     keys = [](_[1])
  4067.     f.write('docsdict = {\n\n')
  4068.     for key in keys[:-1]:
  4069.         f.write('%s :\n' % repr(key))
  4070.         f.write('        """%s\n""",\n\n' % docsdict[key])
  4071.     
  4072.     key = keys[-1]
  4073.     f.write('%s :\n' % repr(key))
  4074.     f.write('        """%s\n"""\n\n' % docsdict[key])
  4075.     f.write('}\n')
  4076.     f.close()
  4077.  
  4078.  
  4079. def read_docstrings(lang):
  4080.     '''Read in docstrings from lang-specific docstring dictionary.
  4081.  
  4082.     Transfer docstrings, translated to lang, from a dictionary-file
  4083.     to the methods of classes Screen and Turtle and - in revised form -
  4084.     to the corresponding functions.
  4085.     '''
  4086.     modname = 'turtle_docstringdict_%(language)s' % {
  4087.         'language': lang.lower() }
  4088.     module = __import__(modname)
  4089.     docsdict = module.docsdict
  4090.     for key in docsdict:
  4091.         
  4092.         try:
  4093.             eval(key).im_func.__doc__ = docsdict[key]
  4094.         continue
  4095.         print 'Bad docstring-entry: %s' % key
  4096.         continue
  4097.  
  4098.     
  4099.  
  4100. _LANGUAGE = _CFG['language']
  4101.  
  4102. try:
  4103.     if _LANGUAGE != 'english':
  4104.         read_docstrings(_LANGUAGE)
  4105. except ImportError:
  4106.     print 'Cannot find docsdict for', _LANGUAGE
  4107. except:
  4108.     print 'Unknown Error when trying to import %s-docstring-dictionary' % _LANGUAGE
  4109.  
  4110.  
  4111. def getmethparlist(ob):
  4112.     '''Get strings describing the arguments for the given object'''
  4113.     argText1 = argText2 = ''
  4114.     if type(ob) == types.MethodType:
  4115.         fob = ob.im_func
  4116.         argOffset = 1
  4117.     else:
  4118.         fob = ob
  4119.         argOffset = 0
  4120.     if type(fob) in [
  4121.         types.FunctionType,
  4122.         types.LambdaType]:
  4123.         
  4124.         try:
  4125.             counter = fob.func_code.co_argcount
  4126.             items2 = list(fob.func_code.co_varnames[argOffset:counter])
  4127.             realArgs = fob.func_code.co_varnames[argOffset:counter]
  4128.             if not fob.func_defaults:
  4129.                 pass
  4130.             defaults = []
  4131.             defaults = list(map((lambda name: '=%s' % repr(name)), defaults))
  4132.             defaults = [
  4133.                 ''] * (len(realArgs) - len(defaults)) + defaults
  4134.             items1 = map((lambda arg, dflt: arg + dflt), realArgs, defaults)
  4135.             if fob.func_code.co_flags & 4:
  4136.                 items1.append('*' + fob.func_code.co_varnames[counter])
  4137.                 items2.append('*' + fob.func_code.co_varnames[counter])
  4138.                 counter += 1
  4139.             
  4140.             if fob.func_code.co_flags & 8:
  4141.                 items1.append('**' + fob.func_code.co_varnames[counter])
  4142.                 items2.append('**' + fob.func_code.co_varnames[counter])
  4143.             
  4144.             argText1 = ', '.join(items1)
  4145.             argText1 = '(%s)' % argText1
  4146.             argText2 = ', '.join(items2)
  4147.             argText2 = '(%s)' % argText2
  4148.  
  4149.     
  4150.     return (argText1, argText2)
  4151.  
  4152.  
  4153. def _turtle_docrevise(docstr):
  4154.     '''To reduce docstrings from RawTurtle class for functions
  4155.     '''
  4156.     import re as re
  4157.     if docstr is None:
  4158.         return None
  4159.     turtlename = _CFG['exampleturtle']
  4160.     newdocstr = docstr.replace('%s.' % turtlename, '')
  4161.     parexp = re.compile(' \\(.+ %s\\):' % turtlename)
  4162.     newdocstr = parexp.sub(':', newdocstr)
  4163.     return newdocstr
  4164.  
  4165.  
  4166. def _screen_docrevise(docstr):
  4167.     '''To reduce docstrings from TurtleScreen class for functions
  4168.     '''
  4169.     import re
  4170.     if docstr is None:
  4171.         return None
  4172.     screenname = _CFG['examplescreen']
  4173.     newdocstr = docstr.replace('%s.' % screenname, '')
  4174.     parexp = re.compile(' \\(.+ %s\\):' % screenname)
  4175.     newdocstr = parexp.sub(':', newdocstr)
  4176.     return newdocstr
  4177.  
  4178. for methodname in _tg_screen_functions:
  4179.     (pl1, pl2) = getmethparlist(eval('_Screen.' + methodname))
  4180.     if pl1 == '':
  4181.         print '>>>>>>', pl1, pl2
  4182.         continue
  4183.     
  4184.     defstr = 'def %(key)s%(pl1)s: return _getscreen().%(key)s%(pl2)s' % {
  4185.         'key': methodname,
  4186.         'pl1': pl1,
  4187.         'pl2': pl2 }
  4188.     exec defstr
  4189.     eval(methodname).__doc__ = _screen_docrevise(eval('_Screen.' + methodname).__doc__)
  4190.  
  4191. for methodname in _tg_turtle_functions:
  4192.     (pl1, pl2) = getmethparlist(eval('Turtle.' + methodname))
  4193.     if pl1 == '':
  4194.         print '>>>>>>', pl1, pl2
  4195.         continue
  4196.     
  4197.     defstr = 'def %(key)s%(pl1)s: return _getpen().%(key)s%(pl2)s' % {
  4198.         'key': methodname,
  4199.         'pl1': pl1,
  4200.         'pl2': pl2 }
  4201.     exec defstr
  4202.     eval(methodname).__doc__ = _turtle_docrevise(eval('Turtle.' + methodname).__doc__)
  4203.  
  4204. done = mainloop = TK.mainloop
  4205. del pl1
  4206. del pl2
  4207. del defstr
  4208. if __name__ == '__main__':
  4209.     
  4210.     def switchpen():
  4211.         if isdown():
  4212.             pu()
  4213.         else:
  4214.             pd()
  4215.  
  4216.     
  4217.     def demo1():
  4218.         '''Demo of old turtle.py - module'''
  4219.         reset()
  4220.         tracer(True)
  4221.         up()
  4222.         backward(100)
  4223.         down()
  4224.         width(3)
  4225.         for i in range(3):
  4226.             if i == 2:
  4227.                 fill(1)
  4228.             
  4229.             for _ in range(4):
  4230.                 forward(20)
  4231.                 left(90)
  4232.             
  4233.             if i == 2:
  4234.                 color('maroon')
  4235.                 fill(0)
  4236.             
  4237.             up()
  4238.             forward(30)
  4239.             down()
  4240.         
  4241.         width(1)
  4242.         color('black')
  4243.         tracer(False)
  4244.         up()
  4245.         right(90)
  4246.         forward(100)
  4247.         right(90)
  4248.         forward(100)
  4249.         right(180)
  4250.         down()
  4251.         write('startstart', 1)
  4252.         write('start', 1)
  4253.         color('red')
  4254.         for i in range(5):
  4255.             forward(20)
  4256.             left(90)
  4257.             forward(20)
  4258.             right(90)
  4259.         
  4260.         tracer(True)
  4261.         fill(1)
  4262.         for i in range(5):
  4263.             forward(20)
  4264.             left(90)
  4265.             forward(20)
  4266.             right(90)
  4267.         
  4268.         fill(0)
  4269.  
  4270.     
  4271.     def demo2():
  4272.         '''Demo of some new features.'''
  4273.         speed(1)
  4274.         st()
  4275.         pensize(3)
  4276.         setheading(towards(0, 0))
  4277.         radius = distance(0, 0) / 2
  4278.         rt(90)
  4279.         for _ in range(18):
  4280.             switchpen()
  4281.             circle(radius, 10)
  4282.         
  4283.         write('wait a moment...')
  4284.         while undobufferentries():
  4285.             undo()
  4286.         reset()
  4287.         lt(90)
  4288.         colormode(255)
  4289.         laenge = 10
  4290.         pencolor('green')
  4291.         pensize(3)
  4292.         lt(180)
  4293.         for i in range(-2, 16):
  4294.             if i > 0:
  4295.                 begin_fill()
  4296.                 fillcolor(255 - 15 * i, 0, 15 * i)
  4297.             
  4298.             for _ in range(3):
  4299.                 fd(laenge)
  4300.                 lt(120)
  4301.             
  4302.             laenge += 10
  4303.             lt(15)
  4304.             speed((speed() + 1) % 12)
  4305.         
  4306.         end_fill()
  4307.         lt(120)
  4308.         pu()
  4309.         fd(70)
  4310.         rt(30)
  4311.         pd()
  4312.         color('red', 'yellow')
  4313.         speed(0)
  4314.         fill(1)
  4315.         for _ in range(4):
  4316.             circle(50, 90)
  4317.             rt(90)
  4318.             fd(30)
  4319.             rt(90)
  4320.         
  4321.         fill(0)
  4322.         lt(90)
  4323.         pu()
  4324.         fd(30)
  4325.         pd()
  4326.         shape('turtle')
  4327.         tri = getturtle()
  4328.         tri.resizemode('auto')
  4329.         turtle = Turtle()
  4330.         turtle.resizemode('auto')
  4331.         turtle.shape('turtle')
  4332.         turtle.reset()
  4333.         turtle.left(90)
  4334.         turtle.speed(0)
  4335.         turtle.up()
  4336.         turtle.goto(280, 40)
  4337.         turtle.lt(30)
  4338.         turtle.down()
  4339.         turtle.speed(6)
  4340.         turtle.color('blue', 'orange')
  4341.         turtle.pensize(2)
  4342.         tri.speed(6)
  4343.         setheading(towards(turtle))
  4344.         count = 1
  4345.         while tri.distance(turtle) > 4:
  4346.             turtle.fd(3.5)
  4347.             turtle.lt(0.6)
  4348.             tri.setheading(tri.towards(turtle))
  4349.             tri.fd(4)
  4350.             if count % 20 == 0:
  4351.                 turtle.stamp()
  4352.                 tri.stamp()
  4353.                 switchpen()
  4354.             
  4355.             count += 1
  4356.         tri.write('CAUGHT! ', font = ('Arial', 16, 'bold'), align = 'right')
  4357.         tri.pencolor('black')
  4358.         tri.pencolor('red')
  4359.         
  4360.         def baba(xdummy, ydummy):
  4361.             clearscreen()
  4362.             bye()
  4363.  
  4364.         time.sleep(2)
  4365.         while undobufferentries():
  4366.             tri.undo()
  4367.             turtle.undo()
  4368.         tri.fd(50)
  4369.         tri.write('  Click me!', font = ('Courier', 12, 'bold'))
  4370.         tri.onclick(baba, 1)
  4371.  
  4372.     demo1()
  4373.     demo2()
  4374.     exitonclick()
  4375.  
  4376.